在Objective-C中的所有對象都通過引用處理(你的變量只是存儲的地址告訴他們存在於內存中的對象)。
所以分配不同的對象,以局部變量,隻影響局部變量:
+ (void) doSome {
// xx is a local variable... you point it to the address returned
// by [[self sharedInstance] myArray]
//
NSMutableArray *xx = [[self sharedInstance] myArray];
// It's probably nil here since the array was never created.
//
if (xx == nil) {
// Here, you're creating a new object and assigning that object's
// address to your local variable xx... this will have absolutely no
// effect on the return value of [[self sharedInstance] myArray]
// which will keep returning nil.
//
xx = [NSMutableArray array];
}
[xx addObject:@"dfdsf"];
}
有幾種解決方案,您可以採用。其中之一就是爲你的陣列使用一個懶惰的初始化器,像這樣:
// Add this property to your class
@property (nonatomic, strong) NSMutableArray* myArray;
+ (void) doSome {
NSMutableArray *xx = [[self sharedInstance] myArray];
[xx addObject:@"dfdsf"];
}
- (NSMutableArray*)myArray
{
if (!_myArray)
{
_myArray = [NSMutableArray array];
}
return _myArray;
}