PDA

View Full Version : Question about initWithCoder: (NSCoder *) encoder




mdeh
Mar 5, 2009, 04:58 PM
All these questions!!! :) Just when I thought things were going to get easier.

I am trying to conceptualize what happens when an object is unarchived.

So, given, Foo.m with a string Object ivar "strVal" which implements <NSCoding>

-(id) initWithCoder: (NSCoder *) decoder
{
strVal = [ [decoder decodeObjectForKey: @"FooStrVal"]retain];
..............


and the documentation that "decodeObjectForKey": Decodes and returns an autoreleased Objective-C object that was previously encoded with.........


and lastly this snippet in main.m

myFoo2 = [ NSKeyedUnarchiver unarchiveObjectWithFile: @"foo.arch"];


Again, given that myFoo2 was **not** created with any of the **magic** words which would imply ownership ( and hence warrant a release method call in main), does not the **retain** call in Foo.m need a release? Or is this a simple matter that the ivar is allocated "memory" during the instantiation of instance, ( if that even makes sense) and the retain simply matches the autorelease of the returned object by the unarchiver?
Sorry if this sounds a little confusing, but my head is spinning :) Clarity would be appreciated.



kainjow
Mar 5, 2009, 07:12 PM
Objects created from unarchiving are autoreleased. There's nothing magical here, it follows the same pattern as any other method does. If you want to keep them around longer, retain it, which needs to be followed up with a release (usually in the dealloc method if you're assigning to an ivar).

mdeh
Mar 5, 2009, 08:24 PM
(usually in the dealloc method if you're assigning to an ivar).

Kick myself!!!!!

Thank you so much...I just could not figure out where that thing was being released, so I came up with a bunch of intricate theories!!!

The joy of learning.

Kainjow...you said that .....unarchiving are autoreleased. There's nothing magical here

Are you saying that the retain is just ordinary, or that autorelease is the way Foundation usually handles an object being returned from a collection, ( or that may be too general a statment?)

kainjow
Mar 5, 2009, 11:19 PM
I'm slightly confused trying to understand where you're coming from with this. You might want to reread this section on memory management:
Object Ownership and Disposal (http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmObjectOwnership.html)

mdeh
Mar 6, 2009, 09:02 AM
I'm slightly confused trying to understand where you're coming from with this.

Thanks kainjow. I guess, if , as the documentation states, the unarchived object should **not** be released by me, the programmer, it makes sense that it is "autoreleased" by it's owner, the class method.

But, the real issue for me was your insight into the release I had already written into the dealloc method.

Your help and input is much appreciated