1

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?

3 Answers 3

3

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.

1
  • The first example is perfectly fine because the array is bound to the NSArrayController. It is also not necessary to implement KVC-compliant array accesor methods because NSArrayController already offers those methods. In other words, this answer should not be the accepted one.
    – Mojo66
    Apr 17, 2019 at 13:02
2

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

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.