Search code examples
iphoneinitializationallocationinstance-variables

Where should I alloc/init my ivar?


If I know that I'm going to use the ivar should I alloc/init it in viewDidLoad like:

if (allPeople_ == nil)
  self.allPeople = [NSArray arrayWithArray:[[selectedObject people] allObjects]];

or should I create a getter method and alloc/init in there:

- (Group *)allPeople {

    if (allPeople_ != nil)
        return allPeople_;

    allPeople_ = [NSArray arrayWithArray:[[selectedObject people] allObjects]];
    return allPeople_;
}

I'm assuming the getter method, with the if-statement, is for lazy-loading, which in my case I wouldn't need to do because I'm definitely using self.allPeople throughout my code.

Extra Question:

If I use the getter method do I actually have to do it this way?

allPeople_ = [[NSArray arrayWithArray:[[selectedObject people] allObjects]] retain];

Solution

  • I would initialize it whenever you are going to use it.

    As for the second question, it depends on how your property is declared if it is declared as retain, and you set it like this:

    self.allPeople =
    

    you will not have to send it a retain message, because the synthetized setter will take care of that for you.

    Do notice self.allPeople is different than just allPeople, if you don't use self you are not accessing it thru the setter, you are accesing the ivar directly and therefore it won't receieve a retain message.