Singleton Class iPhone

Well, I try to avoid global variables, so I read about singleton classes. This is an attempt to install and read the modified array, but the result will be 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 ViewController, I added #import "Content.h", where I am trying to name it:

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

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

NSLog(@"contentArray: %@", [content getArray]);
+3
source share
2 answers

You need to first select and initialize the array. Personally, I would do this in the init method of a content class like this:

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

    return self;
}
+4
source

You never allocate / initialize an array contentArray.

+3
source

Source: https://habr.com/ru/post/1728857/


All Articles