ios C:自定义类的NSArray?

vd8tlhqk  于 9个月前  发布在  iOS
关注(0)|答案(4)|浏览(127)

我试图学习iOS,我来自Java背景,我们可以有特定类的列表/数组,如

List<String> l = new ArrayList<>();
List<MyClass> l = new ArrayList<>();

字符串
看看Objective-C,我可以使用NSArray类来创建immutable数组,但是我如何指定这个NSArrray严格MyClass类型?

q9rjltbz

q9rjltbz1#

据我所知,在Swift-C中没有一个内置的机制来指定放入NSArray的对象的类型,但看起来Swift做了你想要的事情,如果这有帮助的话:
https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html#//apple_ref/doc/uid/TP40014097-CH8-XID_172
在一个稍微相关的注意事项上,这里有一篇关于强制只将特定类型的对象插入到子类NSMutableArray中并在尝试插入 * 错误 * 对象类型时抛出异常的文章:
NSMutableArray - force the array to hold specific object type only

wwwo4jvm

wwwo4jvm2#

遗憾的是,Objective-C中没有泛型。

7nbnzgx9

7nbnzgx93#

你可以使用NSArray<MyClass*> *myClassArray来声明MyClass的数组。如果你想创建一个自己的数组,你可以这样做。

// The only limitation is that MyGenericType must be an object.
// Exclude __covariant if you are doing something with the same interface in
// a different part of your code

@interface MyGenericClass<__covariant MyGenericType> : NSObject

// Your code here

@end

字符串
__covariant的这种用法可以在NSArray和更多的接口中找到。
这就是它在NSArray接口中的使用方式。

@interface NSArray<__covariant ObjectType> : NSObject <NSCopying, NSMutableCopying, NSSecureCoding, NSFastEnumeration>

// the code

@end

// A different part of the code using the same interface, so __covariant is excluded.
@interface NSArray<ObjectType> (NSExtendedArray)

// more code

@end


MyGenericType必须是对象的原因是因为Objective C没有任何类型,所以在实现中使用id。但是数字可以用NSNumber表示。您也可以指定多个__covariants,只需用逗号分隔即可。
或者你可以去调查斯威夫特

xienkqul

xienkqul4#

现在Xcode 7支持一些标准集合的泛型(例如NSArrays)。所以你可以创建一个数组并提供这样的存储对象:

NSArray<NSString*> *myArrayOfStrings;

字符串

相关问题