开发者

NSArray of objects and Casting

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 ob开发者_高级运维jectAtIndex:1];

Or is there a another way to do it kind of like in java where you have ArrayList<A> arr?


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

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.

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's objectAtIndex: returns a variable of type id. This would be roughly equivalent to returning an Object in Java—"we can't guarantee much about this variable's type." In Objective-C however, you can send messages to id variables without the compiler complaining. So, because you know that the array only contains A instances, you're good to send it the name message. For example, the following will compile without warning:

NSString *name = [[array objectAtIndex:0] name];

However, if you want to use dot notation (e.g. [array objectAtIndex:0].name), you'll need to cast the id to an A * as shown here:

NSString *name = ((A *)[array objectAtIndex:0]).name;


This is the way to do it. You can actually do the above operation without casting the return since you're reading it into a NSString anyway.


this is the way:

NSMutableArray  *objectsArray = [[NSMutableArray  alloc] init];

A *a= [[A alloc] init];

[objectsArray addObject:a];

[a release];

You don't need to worry about the proprety type

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜