Reputation: 127
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",[tmpArray 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
Upvotes: 1
Views: 289
Reputation:
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 *
.
Upvotes: 0
Reputation: 27900
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];
Upvotes: 1