Re: Question Re Memory Management in Apps
Re: Question Re Memory Management in Apps
- Subject: Re: Question Re Memory Management in Apps
- From: Philippe Sismondi <email@hidden>
- Date: Tue, 9 Mar 2010 14:47:29 -0500
On 2010-03-09, at 2:01 PM, David Duncan wrote:
> On Mar 8, 2010, at 7:44 PM, Philippe Sismondi wrote:
>
>> Here is my AppController's init method, in which instanceObj is set to an autoreleased MadeObj:
>>
>
>> In other words, the MadeObj instance for AppController's instance variable is created and then immediately dealloc'd. I take this to mean that the autorelease pool it was in was released/drained. If I change the AppController init method to retain instanceMadeObj, the dealloc does not happen.
>
> When you use +alloc/-init on an object however, you are returned an object that you own, thus it will not be deallocated until after you call -release on that object (how soon after will depend on what other objects also own the object).
>
> While your question was sparked by the behavior of an auto release pool, it is really all about object ownership. Because in your example above you don't own the object that you are referencing, it may be deallocated at any time, leaving you with a dangling reference. When you switch to +alloc/-init you instead get an object that you do own, which won't be deallocated until you do release it.
>
> If this is still confusing, I would recommend that you continue taking a look at the Memory Management guide until you've internalized this. It also generally helps to not think about autorelease pools as anything more than an implementation detail until you have gotten all of this down, as they won't make a whole lot of sense to you until you understand how object ownership works.
> --
> David Duncan
> Apple DTS Animation and Printing
>
Thanks, David. I think I get it now. I *mostly* understood before posting, but my mistake - as I see it now - was to make unwarranted assumptions about the autorelease pool state outside the scope of my method. It seems that except for "inner" autorelease pools that I control explicitly, no assumptions can be made about what happens when.
However, unless I am still mistaken, by "deallocated at any time" you mean outside the scope of my init method. That is, I suppose I could have used the autoreleased object within the scope of my init method without it being deallocated out from under me. But since I expect an instance variable to be valid after init returns, I had better retain it.
Is that right?
Thanks again.
- Phil -
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden