没有数组的 NSArrayController

发布于 2024-08-08 16:14:24 字数 393 浏览 2 评论 0原文

我刚刚意识到有两种方法可以使用 NSArrayController。

将控制器绑定到数组并将对象添加到数组中。或者根本不使用任何数组,直接将对象添加到控制器中。

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

或者

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

由于这两个版本都可以很好地满足我的需求,我想知道哪种是正确的使用方法。我想使用数组可能会更好,但是既然 NSArrayController 也能够存储数据,为什么我不应该使用这个功能呢?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

泅人 2024-08-15 16:14:24

不要像第一个示例中那样直接与数组对话。除非您显式发布有关它们的 KVO 通知,否则阵列控制器不会发现您的更改,这是很麻烦并且很容易忘记这样做。

我推荐的方法是绑定数组控制器,然后实现 KVC - 兼容的数组访问器方法为您的属性,并在您的应用中的任何地方使用这些方法(类的 initdealloc 方法除外)。

这样,您的对象就可以改变自己的数组,而无需显式发布 KVO 通知或了解数组控制器。

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.

生死何惧 2024-08-15 16:14:24

两种方式都很好。如果您不给它一个数组,NSArrayController 会维护自己的数组。

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

千秋岁 2024-08-15 16:14:24

NSArrayController 符合 KVO 规范,可与 UI 元素绑定。它还具有对象数组(例如 selectedObject)的附加元数据。 NSArray 不提供这些便利对象。 NSArray 只是一个数组,上面定义了常规数组运算符和方法。如果您不需要与 UI 元素绑定,请使用它。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文