什么是Objective-C的等价物“的toString()”,与使用的NSLog?
-
12-09-2019 - |
题
时有可以在我的自定义类覆盖的方法,使得当
NSLog(@"%@", myObject)
被调用时,它会打印我的对象的字段(或任何我认为重要的)?我想我在寻找的Objective-C相当于Java的toString()
的。
解决方案
它是description
实例方法,声明为:
- (NSString *)description
下面是一个示例实现(由于grahamparks):
- (NSString *)description {
return [NSString stringWithFormat: @"Photo: Name=%@ Author=%@", name, author];
}
其他提示
添加到您的照片类的@implementation
:
- (NSString *)description {
return [NSString stringWithFormat:@"Photo: Name=%@ Author=%@",name,author];
}
有两个功能,可以使用。
- (NSString*)description
当你把你的对象,即这将显示对于NSLog
的参数。其他描述的功能是:
- (NSString*)debugDescription
当你在调试命令窗口po anInstanceOfYourClass
这将被调用。如果你的类没有一个debugDescription
功能,那么就description
将被调用。
请注意的是,基类NSObject
确实有description
实施,但它是相当准系统:它只显示对象的地址。这就是为什么我建议你实现你想要得到的信息进行的任何类description
,特别是如果你在你的代码中使用description
方法。如果你在代码中使用description
,我建议你实现debugDescription
为好,也使debugDescription
更详细。
此将输出可用的声音:
NSLog((@"speechVoices:%", [[AVSpeechSynthesisVoice speechVoices] description] ));
不隶属于 StackOverflow