1. Welcome to the new MacRumors forums. See our announcement and read our FAQ

Special Memory Management Foundation Types

Discussion in 'Mac Programming' started by Jordan72, Nov 24, 2005.

  1. macrumors member

    Some objects in Cocoa you have to add to autorelease pools and others are added by a Foundation method. Take for instance, these NSNumber messages:

    I don't have to release the instance pointed to by myInt, when myInt is assigned to point the an instance the following way:

    id myInt = [NSNumber numberWithInt:100];
    Do I have to release an NSNumber instance if I allocate it this way, since I do use alloc?:

    id myInt = [[NSNumber alloc] initWithInt:100];
    On page 318, second paragraph of Kochan's book Programming in Objective-C it states:

    What does this mean that it is owned by the method that returns it? And, how is it added to the autorelease pool without an explicit message which would do so?
  2. Moderator


    Staff Member

    Basic Cocoa Convention:

    Anything you alloc, init has a retain count of 1 and needs to be released or autoreleased. Any object you get in another way should be autoreleased by whatever code passes it to you.

    It's normally worth sticking to this in your own code to avoid confusion.
  3. Guest


    And also anything you create using 'copy' or 'mutableCopy' needs to be released. Otherwise you can assume they're someone else's problem
    It's added by the autorelease pool immediately before the foundation method returns.
    [returnValue autorelease];
    [return returnValue];
    The foundation classes may actually do this in C but the principle is the same.

    When you autorelease something it doesn't immediately disappear like it would with release. It is in a bunch of objects that will be released soon. This is why you can happily use a autoreleased object in your code but only if you won't need it for long. If there's any chance something you do will take a bit of time to do (like network or i/o access) you should really retain it in case the object is autoreleased whilst you still need it.
  4. macrumors member

    So, if I allocate a NSString and NSNumber in the following ways, is it true that they are not added to the autorelase pool?

    NSNumber * myNum = [[NSNumber alloc] initWithInt:100];
    NSString * myStr = [[NSString alloc] initWithString:@"A string."];
    If they are added, then I don't need to release them. If not, then I must send them a release meassage to manage my programs memory competently.
  5. Moderator


    Staff Member

    Those objects have a retain count of 1 and are not in any autorelease pool so need releasing at some point.
  6. macrumors member

    Thanks for the help. I think I'm all cleared up on that now. I'm sort of paranoid about having the memory thing down from the get go, because I don't want the headaches later.

Share This Page