Assignment does retain?

Discussion in 'iOS Programming' started by marcpage, Oct 14, 2008.

  1. marcpage macrumors newbie

    Oct 14, 2008
    This is really an Objective-C question, but the iPhone is the first platform that forced me to actually use my rusty Objective-C. I am very familiar of C-based CoreFoundation programming.

    In Apple's Custom Table View example (the most advanced of the 5 in the download) there is some code like:

    NSMutableArray *regions = [[NSMutableArray alloc] init];
    ... code that fills in regions ...
    self.displayList = regions;
    [regions release];
    So to me, this looks similar to:

    x= CFCreateMutableArray(...);
    this->x= x;
    Is there an implicit retain on assignment? I see the pattern used a lot, so I assume that is the case. So in my code I could:

    group= [[NSMutableArray alloc] init];
    [displayList addObject:group];
    ... fill in data in group array ...
    [group release]
    What about if I call a C function that returns a CFStringRef?

    NSString *results= CFStringCreate...(...);
    ... handle results ...
    [results release];
    Is that correct?
  2. robbieduncan Moderator emeritus


    Jul 24, 2002
    Any object created with alloc/init or copy will have a retain count of 1. Any object created with any other constructor (or returned from pretty much any other method) will be autoreleased.

    Allocation does not retain. So

    id obj = anObject;
    does not alter the retain count of anObject. Using a setter to set an instance variable in an object will, most likely, retain the object, or perhaps copy it. The dot notation of

    self.displayList = regions;
    tells us that disaplyList is a property. So this is not assignment, rather syntactic sugar for

    [self setDisplayList:regions];
    As this is a setter it will most likely retain regions.

    You say this comes from Apple code so this property is probably synthesized: you will not see any code declaration for setDisplayList. If you look at the property declaration in the header file you will see how the property has been declared. If it is declared as retain then the synthesized setter will retain the object. If it's declared as copy then it'll get copied. Similar for assign.

    I suggest you familiarise yourself fully with the language via the excellent guide. For properties this is the correct section.

    In addition please read all of, and understand, the Cocoa Memory Management Programming Guide as it is critical on the iPhone to understand this.
  3. marcpage thread starter macrumors newbie

    Oct 14, 2008
    Ah, missed that synthesized. Thanks for the references. I've uploaded to my iPod and will start reading.


Share This Page