I tried looking but couldn't find any help.
- (NSArray *)sushiTypes {
return _sushiTypes;
}
- (void)setSushiTypes:(NSArray *)sushiTypes {
[sushiTypes retain];
[_sushiTypes release];
_sushiTypes = sushiTypes;
}
What I would like to know is, while I was working this tutorial, I can't figure out why he is retaining the argument. I tried commenting out that retain statement, and the program works the same, no leaks. So is that just unnecessary?
I'd also like to add the fact that, I called a method like this
self.sushiTypes = [[NSArray alloc]initWithObjects:"objects...];
But when I debug it, instead of going to the -(NSArray *)sushiTypes method, it goes to the setSushiTypes method. Why is this?
You will be pointing _sushiTypes to the value of sushiTypes. Since _sushiTypes is an instance variable, you need to take ownership of this object by retaining it. If you fail to do so and all other owners of this object releases it, this memory will be freed, leaving your instance variable to point to garbage and your app will crash.
It is important to note the order of messages in the setter as well. You need to call
[sushiTypes retain];
first, since _sushiTypes and sushiTypes might be pointing to the same object. If you swop them around and call release first, the memory might be freed before you get a chance to claim ownership.