开发者

NSMutable singleton question

I would like to get some help to sort out the code I've come up with to implement a NSMutableArray singleton.

.h file

@interface MySingleton : NSObject {

    NSMutableArray *globalArray;

}

+ (MySingleton *)instance;

- (NSMutableArray *) getArray;

- (void) addArray:(NSObject *)arrayToAdd;

- (id) init;



.m file

@implementation MySingleton


- (id) init
{
    self = [super init]; 
    globalArray = [[NSMutableArray alloc] init];
    return self;
}


+ (MySingleton *)instance  {

    static MySingleton *instance;

    @synchronized(self) {
        if(!instance) {
            instance = [[MySingleton alloc] init];

        }
    }
    return instance;
}


- (NSMutableArray *) getArray{
    return globalArray;
}



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

    [globalArray addObject:arrayToAdd];  

}

someviewcontroller.m

    MySingleton  *prodInstance = [MySingleton instance];
[prodInstance addArray:tmpArray];
NSLog(@"cnt tmpArray %i",[t开发者_JAVA百科mpArray count]);
NSLog(@"cnt singleton %i",[[prodInstance getArray] count]);

The console will display counts 3 and 1.

I thought [prodInstance getArray] will be the same as the tmpArray.

Thank you


The problem is your addArray method is putting tmpArray inside globalArray, which is apparently not what you want.

I don't think there's really any reason to have addArray at all -- just call getArray to get the global array, and work with that. For example:

// add all objects in tmpArray to prodInstance global array
[[prodInstance getArray] addObjectsFromArray:tmpArray];


In -addArray:, you’re adding the array argument arrayToAdd as a single element in the global array. It looks like you want to add all the elements of the array argument instead, so replace

[globalArray addObject:arrayToAdd];

with

[globalArray addObjectsFromArray:arrayToAdd];

Also, since the argument doesn’t need to be a mutable array, consider changing the parameter type to NSArray *.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜