How is the array updated?


#1

I am new to objective-c and IOS, but have been programming in Visual Basic for a long time.
I can’t understand how does the possessions array get updated with the possession from ItemDetailViewController.

Setting the initial values for possession is clear in this line:

Next, leaving detailViewController, the code is also clear in updating possession:

// "Save" changes to possession [possession setPossessionName:[nameField text]]; [possession setSerialNumber:[serialNumberField text]]; [possession setValueInDollars:[[valueField text] intValue]];

What I don’t understand is how the array is updated, I would expect some code somewhere like this:

[possessions replaceObjectAtIndex:[indexPath row] withObject:[detailViewController possession]; (This is just code to make my point)

I don’t see how the item in possessions gets updated with the new data in possession anywhere.


#2

The answer is in the magic of object pointers.

The PossessionStore is the object that actually keeps the NSArray of possessions. When you ask it for the list:

you’re getting back a pointer to that array, which contains pointers to each of the possessions it contains.

Now, when you set up your ItemDetailViewController, you’re passing it a pointer to an object in that array. When the ItemDetailViewController makes any changes to that object, it’s making changes to the same object that’s stored in the array in the PossessionStore. It may not always be a good idea to work this way; often you will want to work with a copy of the object and then insert it back into the store once you know that the user wants to keep those changes. That’s possible to do, but not what this code does. The most important thing to understand is that when you pass an object pointer as a parameter, that’s just a location in memory that you’re sending into that method. When the method wants to do something with the object that the pointer refers to, it’s going to be talking to the same object that was pointed to by the variable in the code that called that method.