与 NSLog 一起使用的“toString()”的 Objective-C 等价物是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1104746/
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
What is the Objective-C equivalent for "toString()", for use with NSLog?
提问by George Armhold
Is there a method that I can override in my custom classes so that when
是否有我可以在自定义类中覆盖的方法,以便何时
NSLog(@"%@", myObject)
is called, it will print the fields (or whatever I deem important) of my object? I guess I'm looking for the Objective-C equivalent of Java's toString().
被调用,它会打印我的对象的字段(或我认为重要的任何内容)?我想我正在寻找与 Java 的toString().
回答by zakovyrya
It is the descriptioninstance method, declared as:
它是description实例方法,声明为:
- (NSString *)description
Here's an example implementation (thanks to grahamparks):
这是一个示例实现(感谢 grahamparks):
- (NSString *)description {
return [NSString stringWithFormat: @"Photo: Name=%@ Author=%@", name, author];
}
回答by grahamparks
Add this to the @implementationof your Photo class:
将此添加到@implementation您的 Photo 类的 :
- (NSString *)description {
return [NSString stringWithFormat:@"Photo: Name=%@ Author=%@",name,author];
}
回答by teabot
回答by MaddTheSane
There are two functions that you can use.
您可以使用两个功能。
- (NSString*)description
This will be displayed when you put your object as, I.E. a parameter for NSLog. The other description function is:
当您将对象作为 IE 的参数时,这将显示NSLog。另一个描述函数是:
- (NSString*)debugDescription
This will be called when you do po anInstanceOfYourClassin the debug command window. If your class doesn't have a debugDescriptionfunction, then just descriptionwill be called.
这将在您po anInstanceOfYourClass在调试命令窗口中执行时调用。如果您的类没有debugDescription函数,则只会description被调用。
Note that the base class NSObjectdoes have descriptionimplemented, but it is fairly bare-bones: it only displays the address of the object. This is why I recommend that you implement descriptionin any class you want to get info out of, especially if you use the descriptionmethod in your code. If you do use descriptionin your code, I suggest you implement debugDescriptionas well, also making debugDescriptionmore verbose.
请注意,基类NSObject确实已description实现,但它相当简单:它只显示对象的地址。这就是为什么我建议您description在要从中获取信息的任何类中实现,特别是如果您description在代码中使用该方法。如果你确实description在你的代码中使用,我建议你也实现debugDescription,也使debugDescription更冗长。
回答by grigb
This will output the available voices:
这将输出可用的声音:
NSLog((@"speechVoices:%", [[AVSpeechSynthesisVoice speechVoices] description] ));

