如何将 NSObject 从 NSDictionary 转换为 NSString?

Ted*_*edd 2 iphone cocoa cocoa-touch objective-c

NSObject *url = [item objectForKey:@"link"];
Run Code Online (Sandbox Code Playgroud)

这是NSObject来自NSDictionary“项目”。我需要转换NSObjectNSString.

因为我应该使用 url 来串接。

我怎样才能做到这一点?

谢谢你的回复。

Cra*_*tis 5

Max 具有正确的转换语法,但为了安全起见,您需要在运行时进行某种实例检查,因为在 Objective-C 中的编译时无法确保数组或字典中的对象类型是你所期待的:

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);
}
Run Code Online (Sandbox Code Playgroud)