Objective-C:自定义类的 NSArray?

问题描述 投票:0回答:4

我正在努力学习

iOS
,我来自
Java
背景,我们可以拥有特定类的列表/数组,例如

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

看看

Objective-C
,我可以利用
NSArray
类来制作
immutable
数组,但是如何指定这个
NSArrray
MyClass类型的
严格

ios objective-c iphone
4个回答
4
投票

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

NSArray<NSString*> *myArrayOfStrings;

2
投票

据我所知,Objective-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 - 强制数组仅保存特定对象类型


0
投票

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


0
投票

您可以使用

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

© www.soinside.com 2019 - 2024. All rights reserved.