Friday, September 28, 2012

Wy shouldn't I use accessor methodes in an init method?


Wy shouldn't I use accessor methodes in an init method?

First: Apples Documentation says so...

Don’t Use Accessor Methods in Initializer Methods and dealloc
The only places you shouldn’t use accessor methods to set an instance variable are in initializer methods and dealloc. To initialize a counter object with a number object representing zero, you might implement an init method as follows:
- init {

    self = [super init];

    if (self) {

        _count = [[NSNumber alloc] initWithInteger:0];

    }

    return self;

}

To allow a counter to be initialized with a count other than zero, you might implement an initWithCount: method as follows:
- initWithCount:(NSNumber *)startingCount {

    self = [super init];

    if (self) {

        _count = [startingCount copy];

    }

    return self;

}

Since the Counter class has an object instance variable, you must also implement a dealloc method. It should relinquish ownership of any instance variables by sending them a release message, and ultimately it should invoke super’s implementation:
- (void)dealloc {

    [_count release];

    [super dealloc];

}



What stackoverflow says? 

  • It's basically a guideline to minimize the potential for bugs.
  • It is all about using idiomatically consistent code. If you pattern all of your code appropriately there are sets of rules that guarantee that using an accessor in init/dealloc is safe.





What Big Nerd Ranch guide says?
"..In most cases, there is a little reason to do one over the other, but it makes for a great argument. The argument goes like this: The assign guy says, "You can't use an accessor method in an init method! The accessor asumes that the object is ready for work, and it isn't ready for work until after the init method is complete." Then the accessor method guy says, "Oh, come on. In the real world that is almost never an issue. My accessor method might be taking care of other stuff for me. I use my accessor anytime I set that variable." In reality, either approach will work in the cast majority of cases. 

No comments:

Post a Comment