且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Cocoa / Objective-C中有一个类似的列表吗?

更新时间:2023-11-28 23:47:16

想在Cocoa应用程式中使用这个程式通常是设计薄弱的标志。

Wanting this in a Cocoa app is often a sign of a weak design.

NSArray 是不可变的,所以它不会指向任何对象,并且可能已经包含正确的对象,当交给你。我认为你更担心的是一个 NSMutableArray ,你认为你的代码的其他部分可能会添加错误的对象排序。但是看看Cocoa本身;

NSArray is immutable, so it will not "take a pointer to any object" and presumably already contains the correct objects when handed to you. What I assume you're more worried about is an NSMutableArray where you think other parts of your code might add the wrong sort of object. But have a look at Cocoa itself; it's incredibly rare to expose a mutable array as part of a class's design.

相反,你通常会暴露一个 NSArray 以及用于修改该阵列的几种方法。

Instead, you generally expose an NSArray and a couple of methods for modifying that array. Something along the lines of:

@class Foo : NSObject
- (NSArray *)bars;
- (void)addBar:(Bar *)bar;
- (void)removeBar:(Bar *)bar;
@end

这通常通过编译器警告来停止错误的对象,那么当然你可以在 -addBar: -removeBar:中添加断言。

This generally stops wrong objects being inserted simply by having a compiler warning, and then of course you can add assertions within -addBar: and -removeBar: if you wish too.