Devfly
Devfly

Reputation: 2495

What happens when a object is assigned to another object?

For example:

myVC.bunnies = self.myBunnies;

or

[self getBunniesWithCompletion:^(NSArray *bunnies) {
     self.myBunnies = bunnies;
}];

Is the object copied, or it's just its reference that is copied, and if it gets destroyed everything will break?

The property is declared like so:

@property (strong, nonatomic) NSArray *myBunnies;

Upvotes: 0

Views: 81

Answers (2)

AliSoftware
AliSoftware

Reputation: 32681

It totally depends on the way you declared the property:

  • @property(strong) : the object reference count is increased, meaning that the object self keeps a reference to the affected object so that this object is not released (until the reference has been released by setting it to nil)
  • @propery(weak) : the object reference is simply assigned but the reference count is not increased, meaning that self does not retain a reference to it
  • @property(copy) : the object is copied (using <NSCopying>'s copy method) and thus a new instance is stored, independant from the first one

I strongly recommand you to read the Advanced Memory Managment Programming Guide in the Apple Doc. It is not totally up-to-date as some parts of the doc still describe the way it works before ARC was the standard, but it's still always interesting to read to understand those mecanisms.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726639

When you do this assignment, a reference is copied, and a reference count is incremented. All of this is done implicitly through ARC, because you declared your property strong.

If you would like a copy to be made, change the declaration to

@property (copy, nonatomic) NSArray *myBunnies

This would be more expensive, but the array inside your object would be insulated from the array passed into the setter.

Upvotes: 2

Related Questions