views:

115

answers:

3

I just realized there are two ways to use a NSArrayController.

Bind the Controller to and Array and add objects to the Array. Or don't use any Array at all and add objects directly to the Controller.

[racesArray addObject: [[Race alloc] initWithName:@"Human"] ];

Or

[myRacesController addObject: [[Race alloc] initWithName:@"Human"] ];

Since both version work fine for my needs I wonder which is the right way to use it. I guess using an Array might be better but since the NSArrayController is also able to store data why should I not use this feature?

+1  A: 

Both ways are fine. If you don't give it an array, NSArrayController maintains its own.

ianh
A: 

The NSArrayController is KVO compliant for binding with UI elements. It also has additional meta data for an array of objects such as selectedObject. These convenience objects are not available with NSArray. NSArray is just an array with the regular array operators and methods defined on it. Use it if you don't have need to bind with UI elements.

Meehsa
+1  A: 

Don't directly talk to the array like you do in your first example. The array controller won't find out about your changes unless you explicitly post KVO notifications about them, which is a hassle and is easy to forget to do.

The way I recommend is to bind the array controller, then implement KVC-compliant array accessor methods for your property, and use those everywhere in your app (except in the class's init and dealloc methods).

That way, the object can mutate its own array without having to explicitly post KVO notifications or know about the array controller.

Peter Hosey