Exiting cleanly the init method under ARC

  • Hello,

    Under non-ARC, an init method may be implemented like this:

    - (id)init
    {
        self = [super init];

        if (self) {
            if (<somecondition != good>) {
                [self release];
                return nil;
            }

            // Initialize ivars here as usual...
        }

        return self;
    }

    However, if something critical happens within the init method when ARC is activated, what would be the proper way to exit? Would it look like this?:

    - (id)init
    {
        self = [super init];

        if (self) {
            if (<somecondition != good>) {
                // Cleanup here if needed...
                return nil;
            }
        }

        return self;
    }

    Thanks,

    -- Tito
  • On Jun 27, 2012, at 09:12 , Tito Ciuro wrote:

    > However, if something critical happens within the init method when ARC is activated, what would be the proper way to exit? Would it look like this?:
    >
    > - (id)init
    > {
    > self = [super init];
    >
    > if (self) {
    > if (<somecondition != good>) {
    > // Cleanup here if needed...
    > return nil;
    > }
    > }
    >
    > return self;
    > }

    Yes, just return nil.

    Like other local variables, 'self' will be released automatically (if non-nil) at exit from its scope, which is the entire method in this case. Because this is an 'init'-family method, the return value is retained (if non-nil) on execution of the 'return' statement.

    If you put those 2 behaviors together, you'll see that your ARC code has the same memory management effect as your non-ARC code, no matter which 'return' statement is executed.
  • Thanks Quincey!

    On Jun 27, 2012, at 9:54 AM, Quincey Morris wrote:

    > On Jun 27, 2012, at 09:12 , Tito Ciuro wrote:
    >
    >> However, if something critical happens within the init method when ARC is activated, what would be the proper way to exit? Would it look like this?:
    >>
    >> - (id)init
    >> {
    >> self = [super init];
    >>
    >> if (self) {
    >> if (<somecondition != good>) {
    >> // Cleanup here if needed...
    >> return nil;
    >> }
    >> }
    >>
    >> return self;
    >> }
    >
    > Yes, just return nil.
    >
    > Like other local variables, 'self' will be released automatically (if non-nil) at exit from its scope, which is the entire method in this case. Because this is an 'init'-family method, the return value is retained (if non-nil) on execution of the 'return' statement.
    >
    > If you put those 2 behaviors together, you'll see that your ARC code has the same memory management effect as your non-ARC code, no matter which 'return' statement is executed.
    >
    >
previous month june 2012 next month
MTWTFSS
        1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30  
Go to today