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屋!