在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;
}