Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to assign a property to the result of an autoreleased initializer while using ARC?

Let's say I have a strong property like so:

  @interface Foo
    @property (strong, nonatomic) NSArray *myArray;
  @end

And, in my initializer, I set myArray like so:

myArray = [NSArray array];

Is this safe? Will ARC take care of properly retaining myArray for me?

The reason I ask is that I have a project where myArray isn't properly retained in this scenario, and I get a bad memory access down the road.

But, if I use

 myArray = [[NSArray alloc] init];

then all is well.

like image 986
jimothy Avatar asked Jan 17 '12 21:01

jimothy


1 Answers

Yes, ARC will automatically retain it for you.

The way to think of ARC is this: If you have a strong pointer to an object, then it is guaranteed to stay alive. When all pointers (well, all strong pointers) to an object go away, the object will die.

From the description of your problem, it sounds like ARC isn't properly enabled in the file where you're executing that code. Regardless, I'd recommend running your app with Instruments, using the "Zombies" template. That will let you see the full retain/release history of that object, and you should be able to figure out where things are going wrong.

like image 183
BJ Homer Avatar answered Nov 15 '22 07:11

BJ Homer