Question about initWithCoder: (NSCoder *) encoder

Discussion in 'Mac Programming' started by mdeh, Mar 5, 2009.

  1. mdeh macrumors 6502

    Jan 3, 2009
    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

    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.
  2. kainjow Moderator emeritus


    Jun 15, 2000
    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).
  3. mdeh thread starter macrumors 6502

    Jan 3, 2009
    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. said that
    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?)
  4. kainjow Moderator emeritus


    Jun 15, 2000
    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
  5. mdeh thread starter macrumors 6502

    Jan 3, 2009
    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

Share This Page