user2568508
user2568508

Reputation:

NSArray in Objective C - what does it contain

When I have such code:

Fruit *fruit= [[Fruit alloc] init];

// This is effectively two different things right, one is "fruit" - the pointer, and another thing is the object it is pointing to (the one that was allocated using alloc/init) - though not directly visible 

When I add this to NSArray:

[myArray addObject: fruit];

What gets added to the array is actually a pointer to the Fruit class object, right?

Upvotes: 1

Views: 285

Answers (3)

vignesh kumar
vignesh kumar

Reputation: 2330

As you know if *var is the value at the pointer then var is pointer (as in c language)

which means if *fruit is the object then you are adding the pointer fruit to the array like [myArray addObject: fruit];

Upvotes: 0

trojanfoe
trojanfoe

Reputation: 122391

Yes, a copy of the pointer, which points to a valid initialized object, so the following won't cause an issue (under ARC, at least):

Fruit *fruit= [[Fruit alloc] init];
[myArray addObject: fruit];
fruit = nil;     // OK, array still contains a valid Fruit object

Upvotes: 2

tanz
tanz

Reputation: 2547

Yes it adds a strong pointer to your object.

Using ARC remember that an object is automatically dealloc'd when there are no strong pointers to them. This means that by design if you use ARC you need to set any pointer to an object that you have to "nil" in order to deallocate it. This includes for instance a pointer stored in an NSArray.

Upvotes: 0

Related Questions