Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton Class iPhone

Ok, I'm trying to avoid global variables, so I read up on singleton classes. This is a try to set and read a mutable array, but the result is null.

//Content.h

@interface Content : NSObject {
    NSMutableArray *contentArray;
}

+ (Content *) sharedInstance;

- (NSMutableArray *) getArray;
- (void) addArray:(NSMutableArray *)mutableArray;


@end

.

//Content.m

@implementation Content



static Content *_sharedInstance;

+ (Content *) sharedInstance
{
    if (!_sharedInstance)
    {
        _sharedInstance = [[Content alloc] init];
    }

    return _sharedInstance;
}

- (NSMutableArray *) getArray{
    return contentArray;

}

- (void) addArray:(NSMutableArray *)mutableArray{

    [contentArray addObject:mutableArray];  

}

@end

And in a ViewController I added #import "Content.h", where I try to call this:

NSMutableArray *mArray = [NSMutableArray arrayWithObjects:@"test",@"foo",@"bar",nil];

Content *content = [Content sharedInstance];
[content addArray:mArray];

NSLog(@"contentArray: %@", [content getArray]);
like image 952
scud Avatar asked Dec 05 '25 10:12

scud


2 Answers

You need to alloc and init the array first. Personally I'd do it in the init method of the content class like so:

-(id)init{
    if(self = [super init]){
        …the rest of your init code… 
        contentArray = [[NSMutableArray alloc] init];
    }

    return self;
}
like image 160
James Avatar answered Dec 07 '25 01:12

James


You never actually alloc/initialise the contentArray array.

like image 43
hanno Avatar answered Dec 07 '25 00:12

hanno



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!