scud
scud

Reputation: 1157

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]);

Upvotes: 3

Views: 2393

Answers (2)

James
James

Reputation: 5820

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;
}

Upvotes: 4

hanno
hanno

Reputation: 6513

You never actually alloc/initialise the contentArray array.

Upvotes: 3

Related Questions