NSArrayController without Array
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 si开发者_如何学Cnce the NSArrayController is also able to store data why should I not use this feature?
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, your object can mutate its own array without having to explicitly post KVO notifications or know about the array controller.
Both ways are fine. If you don't give it an array, NSArrayController
maintains its own.
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.
精彩评论