1

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?

  • 1
    In objective c, you don't have addObject method for NSArray. Unless you can use NSMutableArray for addObject method. Yes, if you use addObject Fruit to NSMutableArray, it contains the pointer that links the object Fruit. – Funny Jan 21 '14 at 11:32

3 Answers3

2

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
trojanfoe
  • 120,358
  • 21
  • 212
  • 242
  • I have a question regardless this topic what's happened when you do [myArray addObject:&fruit]; ? Do you add a week pointer? – Greg Jan 21 '14 at 11:23
  • @trojanfoe: ok, maybe stupid question: but why have this pointers at all like here in obj c? why not have for example all objects put on stack or somewhere else :) –  Jan 21 '14 at 11:27
  • @Greg you may wanna read this: http://stackoverflow.com/questions/9336288/nsarray-of-weak-references-to-objects-under-arc – Desdenova Jan 21 '14 at 11:28
  • @user2568508 They are pointers to dynamically allocated memory on "the heap". Stack size is limited and the stack changes as functions are called, etc., so it's no the place to store objects that you want to persist throughout the process's lifetime. – trojanfoe Jan 21 '14 at 11:32
  • @trojanfoe: ok ........ So NSArray basically stores pointers to the objects, not the objects themselves ... –  Jan 21 '14 at 11:33
  • @user2568508 Yes, however it's common to talk about a pointer-to-object as being "the object". – trojanfoe Jan 21 '14 at 11:35
  • @trojanfoe: Yep I encountered this, although it is a bit confusing.... one may agree :) –  Jan 21 '14 at 11:37
0

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.

tanz
  • 2,557
  • 20
  • 31
0

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

vignesh kumar
  • 2,310
  • 2
  • 25
  • 39