NSArray对象和Casting [英] NSArray of objects and Casting
问题描述
我有一个 A
的类,其属性为 NSString * name
。如果有 NSArray
并在此数组中添加许多 A
对象,那么每次检索对象时都需要进行强制转换吗?即。
I have a class A
with a property NSString *name
. If have an NSArray
and add many A
objects into this array, is casting necessary each time I retrieve an object? i.e.
NSString* n = (NSString*)[arr objectAtIndex:1];
还是有另一种方法可以在java中使用的ArrayList< a取代; arr
?
Or is there a another way to do it kind of like in java where you have ArrayList<A> arr
?
推荐答案
NSArray
不要存储有关其中包含的对象类型的信息。如果您确定数组中的对象类型,则可以隐式或显式执行强制转换:
NSArray
do not store information about the types of objects contained in them. If you know for sure the types of objects in your array, you can perform a cast, either implicitly or explicitly:
NSString *n = [arr objectAtIndex:1]; // implicit type conversion (coercion) from id to NSString*
NSString *n = (NSString *)[arr objectAtIndex:1]; // explicit cast
隐式和显式转换之间的运行时成本没有区别,这只是一个问题样式。如果你输入的类型不对,那么很可能会发生的事情是你会把可怕的无法识别的选择器发送到实例0x12345678
异常。
There's no difference in runtime cost between implicit and explicit casts, it's just a matter of style. If you get the type wrong, then what is very likely going to happen is that you'll get the dreaded unrecognized selector sent to instance 0x12345678
exception.
如果您有不同类型对象的异构数组,则需要使用 isKindOfClass:
测试对象类的方法:
If you have a heterogeneous array of different types of objects, you need to use the isKindOfClass:
method to test the class of the object:
id obj = [arr objectAtIndex:1];
if ([obj isKindOfClass:[NSString class] ])
{
// It's an NSString, do something with it...
NSString *str = obj;
...
}
这篇关于NSArray对象和Casting的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!