在Cocoa / Objective-C中有一个类似的列表吗? [英] Is there anything like a generic list in Cocoa / Objective-C?
问题描述
我在C#中真正喜欢的是通用列表。可以只包含一种类型的对象的列表。
在Cocoa / Objective-C中有一个类似的列表吗?到目前为止我只知道 NSArray
谁将指向任何对象的指针。
What I really like in C# are generic lists. A list that can contain only one type of objects.
Is there something like a generic list in Cocoa/Objective-C? As far I only know NSArray
who will take a pointer to any object.
推荐答案
想在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.
这篇关于在Cocoa / Objective-C中有一个类似的列表吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!