Tedd
Tedd

Reputation: 21

How to convert a NSObject from NSDictionary into NSString?

NSObject *url = [item objectForKey:@"link"];

This is a NSObject from NSDictionary "item". I need to convert NSObject to NSString.

Because I should use url to string.

How can I do that?

Thank you for replying.

Upvotes: 2

Views: 7830

Answers (2)

Craig Otis
Craig Otis

Reputation: 32054

Max has the correct casting syntax, but to be safe you'll want to do some kind of instance check at runtime, since it's not possible at compile-time in Objective-C to ensure that the type of an object in an array or dictionary is what you're expecting:

NSObject *obj = [item objectForKey:@"link"];
if ([obj isKindOfClass:[NSString class]]) {
   NSString *stringValue = (NSString *)obj;
   // Do something with the NSString
} else {
   // You can alternatively raise an NSException here.
   NSLog(@"Serious error, we expected %@ to be an NSString!", obj);
}

Upvotes: 5

Max
Max

Reputation: 16719

NSString *url = (NSString*)[item objectForKey:@"link"];

Upvotes: 4

Related Questions