objective-c 将 NSObject 转换为 NSString
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/720249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Casting an NSObject to NSString
提问by Joel Hooks
I am working through the Stanford iPhone classand I can't figure out why I am getting a compiler warning. I assume I need to cast my object to NSString, but I get an error when I try to do so. The code runs and gives me the expected output, but the warning bothers me.
我正在学习斯坦福 iPhone 课程,但我不明白为什么我会收到编译器警告。我假设我需要将我的对象转换为 NSString,但是当我尝试这样做时出现错误。代码运行并给了我预期的输出,但警告让我烦恼。
NSLog(@"lowerCaseString is: %@", [object lowercaseString]);
This runs with the warning: 'NSObject' may not respond to '-lowerCaseString'
这与警告一起运行:“NSObject”可能不会响应“-lowerCaseString”
NSLog(@"lowerCaseString is: %@", [(NSString)object lowercaseString]);
This throws an error: conversion to non-scalar type requested
这会引发错误:已请求转换为非标量类型
回答by Adam Alexander
I believe this will do what you need:
我相信这会做你需要的:
NSLog(@"lowerCaseString is: %@", [(NSString *)object lowercaseString]);
Note I just added a * to your second line of code to make a pointer to NSString.
注意我只是在你的第二行代码中添加了一个 * 来创建一个指向 NSString 的指针。
回答by Chuck
Why is object declared as an NSObject if it's supposed to be an NSString? If you intend to call NSString methods on it, declare it as an NSString or leave it as an id. Then you won't get errors.
如果对象应该是 NSString,为什么要声明为 NSObject?如果您打算对其调用 NSString 方法,请将其声明为 NSString 或将其保留为 id。那么你不会得到错误。

