views:

307

answers:

2

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]);
+2  A: 

You never actually alloc/initialise the contentArray array.

hanno
You're totally right, thank you
hecta
+3  A: 

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;
}
James Raybould
Perfect, thanks for the code
hecta