开发者

id type to NSString

is there any way by which I can change an id type to NSString object? note the following line of my code.

NS开发者_高级运维String *value = [appDelegate.bird_arr objectAtIndex:rowClicked] ;

in this appDelegate is object of my AppDelegate class in a navigation based program and bird_arr is object of NSMutableArray. I want to use the string written in row which is clicked. But objectAtIndex: returns id type. Do we have any way to change this id type to NSString or any other way by which I can collect string inside the specific row?


yep, just cast it

NSString *value = (NSString *)[appDelegate.bird_arr objectAtIndex:rowClicked];

If you want to double check that it really is an NSString use

[someId isKindOfClass:[NSString class]]


An id could be a pointer any object, and it will get promoted to any object pointer type automatically (sort of like void * in C). The code you show there looks correct. There's no need for an explicit cast, though you could add one if you really want to.

If the object you're getting out of the array is not, in fact, an NSString, you will have to do some other work to get the object you want.


"id type" just tells us the return value is an object — nothing beyond that. It could already be an NSString object, or it could be something else. If all the objects in this array are strings, your work is done. If they're something else, you need some way to get that something else into a string.


in Foundation all objects inherits NSObject class which has methods like:

+ (NSString *)description;

so you can make it like this:

NSString *value = [[appDelegate.bird_arr objectAtIndex:rowClicked] description];


assuming that the object is an NSString, casting to NSString* should work fine:

NSString* value = (NSString*)[appDelegate.bird_arr objectAtIndex:rowClicked];
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜