Why is todoItems not alloc-inited?


In the Cocoa version of TahDoodle, the todoItems mutable array is lazily created like this:

- (IBAction)createNewItem:(id)sender; { if(!todoItems) { todoItems = [NSMutableArray array]; } ... }

Any other time it’s created in this chapter, it’s using [NSMutableArray array]. Shouldn’t this be returning an autoreleased instance? Why isn’t it created using [[NSMutableArray alloc] init] like it is in the previous chapter?


You should read the class references for NSArray and NSMutableArray.

[NSMutableArray array] is a class method (a convenience method) that does an alloc and an init on your behalf but returns an autoreleased object instead (in MRC.)

AIso if todoItems is a property, it is better to write: self.todoItems = [NSMutableArray array]:

- (IBAction)createNewItem:(id)sender;
   if(!todoItems) {
      self.todoItems = [NSMutableArray array];


Thanks for the answer ibex. I’m aware that [NSMutableArray array] is allocing and initing behind the scenes. My question was more about the memory management.

As you point out, it would be more usual (for memory management) to do a self.todoItems = [NSMutableArray array], as that would retain it. In the book, there’s a straight assign to a bare ivar, no properties involved. As you say, this returns an autoreleased mutable array.

So why is this array never released. The app runs fine and todoItems seems to stick around, even though it’s never retained. Is this something to do with a document-based app? Is it something to do with ARC?


Yes, the ARC magic is happening here: the object ([NSMutableArray array]) is being retained until it is no longer needed.


Aha! I always think of ARC as releasing things that are no longer needed. I didn’t know that it also retained things that are.