Question

While reading about classes in Objective-C I found that in some cases people advice that when implementing the init method to do it as:

- (id) init {

    if ( self = [super init] ) { 

        ...
    }

    return self; 
}

While others don't refer this. Which one is correct one?

Also, when defining setters most of the times they simply consist in an assignment but sometimes they appear as:

- (void) setCaption: (NSString*)input {

  [caption autorelease];
  [input retain];
  caption = input;
}

Once again, which one is the best approach? Does ARC has some effect on this? If I use ARC, I don't need to use autoreleaseas above?

thanks!

Was it helpful?

Solution

Straight from Apple's official documentation:

There are several critical rules to follow when implementing an init... method that serves as a class’s sole initializer or, if there are multiple initializers, its designated initializer (described in “Multiple Initializers and the Designated Initializer”):

  • Always invoke the superclass (super) initializer first.

  • Check the object returned by the superclass. If it is nil, then initialization cannot proceed; return nil to the receiver.

  • When initializing instance variables that are references to objects, retain or copy the object as necessary (in memory-managed code).

  • After setting instance variables to valid initial values, return self unless:

    • It was necessary to return a substituted object, in which case release the freshly allocated object first (in memory-managed code).

    • A problem prevented initialization from succeeding, in which case return nil.


Concerning the second issue, you typically don't have to implement the accessor methods by hand, but in case you must or want, here's a useful reference: Explicit getters/setters for @properties (MRC)

OTHER TIPS

1

In general: call super.

But pay attention to dedicated initialiser and don't blindly override stuff

see: http://macdevelopertips.com/objective-c/objective-c-initializers.html

2

if you use arc, you don't have to do manual memory management so the setter would be one line. Most of the time auto-synthezing it is fine

I know that a reason calling [super init] is to actually initialize something belong to super class. I found a better answer given by @gabrielePetronella while I wrote my answer. Please check that out.

And, If you use ARC, you don't use a set of memory management methods such as [release], [autorelease]. Even though you try to use those methods, Xcode sends you a compile error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top