ikzjfr0
ikzjfr0

Reputation: 767

property value issue in iOS Singleton

In below code, I try to add new object into myArray.However, after calling doSome method, the value of myArray is still nil, why?

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

}

Upvotes: 0

Views: 48

Answers (2)

clearscreen
clearscreen

Reputation: 2027

All objects in Objective-C are handled by reference (your variables simply store an address that tell them where the object exists in memory).

So assigning a different object to a local variable, only affects that local variable:

+ (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"];
}

There are several solutions you can adopt. One of them is to use a lazy initializer for your array, like this:

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

Upvotes: 1

Jonah
Jonah

Reputation: 17958

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

You have a pointer to a mutable array named xx. Currently xx points to whatever object myArray returned.

xx = [NSMutableArray array];

Here you reassign xx to point to a new array. While xx has changed to point to a new object nothing has changed your 'sharedInstanceobject or whichever object itsmyArray` property refers to. In order to change the array stored in this singleton you would need to update the property on that shared instance. Perhaps with something like:

[[self sharedInstance] setMyArray:xx];

Upvotes: 2

Related Questions