Question

I created a class named as Tutoral which is a sub class of NSObject, and it has following synthesized properties Title and Url.Then in my viewcontroller I created an instance of the Tutorial class.I also Created an NSMutableArray object and initialised. I added my tutorial object instance to the array. Then I set the properties such as Title = "mytitle" and Url = "myurl". In another place I fetched the tutorial object instance from the array and NSLog its Title and Url property values.It shows "mytitle" and "myurl" respectively. My confusion is that why tutorial object instance which is inside the arry shows its property values. The tutorial object properties are set after that object is added to the array. Follwing are my tested code.

NSMutableArray *newTutorials = [[NSMutableArray alloc] initWithCapacity:0];

Tutorial *tutorial = [[Tutorial alloc] init];

[newTutorials addObject:tutorial];

tutorial.title = @"mytitle";

tutorial.url = @"myurl";

Tutorial *objNew = [newTutorials objectAtIndex:0];

NSLog(@"Title %@",objNew.title);

NSLog(@"Url %@",objNew.url);
Was it helpful?

Solution 2

When the following line of code executed,

[newTutorials addObject:tutorial];

What it does is , it add the address (reference) of tutorial object which you created in the previous line to the array newTutorials.

Your confusion is this : " You haven't set the values for the tutorial object inside the array but why is it displaying mytitle and myurl when you NSLoged the propeties of tutorials?" The answer is simple "You've not stored the tutorial object inside the array but you have stored a reference to the tutorial object"

Since when you've stored the reference and you've done the following to tutorial object :

tutorial.title = @"mytitle";

tutorial.url = @"myurl";

When you try to print the properties of the reference stored in the array, it prints mytitle and myurl because that is what you've assigned to the actual object's properties.

OTHER TIPS

When you add an object to an array, the array just keeps a reference to that object (a pointer). It doesn't create a copy of that object.

So, in the code example above, you're always dealing with the same instance of Tutorial:

  • First, you create a new Tutorial with alloc and init, and store a reference to it with the tutorial pointer.
  • Then you add it to your array. Your array retains the object, which means it keeps a reference to it.
  • Then you set the title and url properties of your existing object.
  • Then you grab another reference to the same object, and call it objNew. You get this reference by asking the array for a pointer to its first object.
  • You then print the properties of the object.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top