我正在努力学习
iOS
,我来自Java
背景,我们可以拥有特定类的列表/数组,例如
List<String> l = new ArrayList<>();
List<MyClass> l = new ArrayList<>();
看看
Objective-C
,我可以利用NSArray
类来制作immutable
数组,但是如何指定这个NSArrray
是MyClass
类型的严格?
现在 Xcode 7 支持标准集合的某种泛型(例如 NSArrays)。所以你可以创建一个数组并提供像这样的存储对象:
NSArray<NSString*> *myArrayOfStrings;
据我所知,Objective-C 中没有内置机制来指定放入 NSArray 中的对象类型,但看起来 Swift 可以满足您的需求(如果这有帮助的话):
在一个稍微相关的注释中,这里有一篇不错的文章,内容是关于强制仅将某种类型的对象插入到子类 NSMutableArray 中,并在尝试插入错误对象类型时抛出异常:
遗憾的是 Objective-C 中没有泛型。
您可以使用
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没有any类型,所以你在实现中使用id
代替。但数字可以用NSNumber
来表示。您还可以指定多个__covariants
,只需用逗号分隔即可。
或者你可以看看 swift。