iOS Singleton中的属性值问题

时间:2014-09-11 01:35:18

标签: ios properties singleton

在下面的代码中,我尝试将新对象添加到myArray中。但是,在调用doSome方法之后,myArray的值仍为零,为什么?

+ (void) doSome {
  NSMutableArray *xx = [[self sharedInstance] myArray];
  if (xx == nil) {
    xx = [NSMutableArray array];
  }
  [xx addObject:@"dfdsf"];

}

2 个答案:

答案 0 :(得分:2)

NSMutableArray *xx = [[self sharedInstance] myArray];

您有一个指向名为xx的可变数组的指针。目前xx指向返回的任何对象myArray

xx = [NSMutableArray array];

在此重新分配xx以指向新数组。虽然xx已更改为指向新对象,但您的'sharedInstance object or whichever object its myArray`属性指的是没有任何更改。要更改存储在此单例中的数组,您需要更新该共享实例上的属性。也许有类似的东西:

[[self sharedInstance] setMyArray:xx];

答案 1 :(得分:1)

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