Cluster initializers with ARC
Asked Answered
S

2

9

Parsing through this document on class clusters, NSNumber implements initWithChar: in roughly the following manner:

- (id)initWithChar:(char)c
{
    [self release];
    return [[__NSCharNumber alloc] initWithChar:c];
}

Similarly, you could use this pattern for initializing views from a Nib:

- (id)initWithFrame:(CGRect)frame
{
    id realSelf = [[self class] nib] instantiateWithOwner:nil options:nil][0];
    realSelf.frame = frame;
    [self release];
    return realSelf;
}

I'm wondering, does ARC manage the releasing of the unreturned self in these cases? Is it documented anywhere?

Seabolt answered 23/9, 2013 at 17:18 Comment(1)
That's "class clusters", not "cluster classes."Aversion
S
6

Found the details in the clang documentation.

init implicitly uses the __attribute__((ns_consumes_self)) attribute, meaning that while self is defined as __strong id self, the initial assignment does not perform a retain. This means as soon as self is reassigned or the function terminates, self will be released using standard strong rules.

To get an +1 out, there is an implicit __attribute((ns_returns_retained)) which prevents the returned object from being released at the end.

At a high level, ARC plans to release the initial value of self one extra time by the end of the function, while also retaining the return value, maintaining its +1 output.

Seabolt answered 23/9, 2013 at 22:2 Comment(2)
Thank you, Brian. Could you please show, how the code would look like?Chlorinate
@Slabko There's nothing to it really other than returning a new instance of a subclass in initWith.... I've put together a couple examples of class clusters here: github.com/bnickel/Cluster-Initializer-ExamplesSeabolt
R
3

It would fall under standard ARC object ownership rules, whereby the "unreturned self" would end up without any strong references and would therefore be automatically released for you when it falls out of scope.

Rhona answered 23/9, 2013 at 18:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.