2014-09-11 49 views
0

在下面的代碼中,我嘗試將新對象添加到myArray.However,但在調用doSome方法後,myArray的值仍爲零,爲什麼?iOS中的屬性值Singleton

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

}

回答

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