什么是"toString()"的Objective-C等价物,与NSLog一起使用?

Geo*_*old 167 objective-c tostring nslog

是否有一种方法可以在我的自定义类中覆盖,以便何时

      NSLog(@"%@", myObject) 
Run Code Online (Sandbox Code Playgroud)

被称为,它将打印我的对象的字段(或任何我认为重要的)?我想我正在寻找Java的Objective-C等价物toString().

zak*_*rya 247

它是description实例方法,声明为:

- (NSString *)description
Run Code Online (Sandbox Code Playgroud)

这是一个示例实现(感谢grahamparks):

- (NSString *)description {
   return [NSString stringWithFormat: @"Photo: Name=%@ Author=%@", name, author];
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,如果您使用的是CoreData,那么`description`属性[保留](http://stackoverflow.com/questions/4717519/why-cant-i-use-description-as-an-attribute-name-for- a-core-data-entity)...并将提供有用的调试信息!在这种情况下,您需要提出自己独特的方法名称. (5认同)

gra*_*rks 35

将其添加到@implementationPhoto类中:

- (NSString *)description {
   return [NSString stringWithFormat:@"Photo: Name=%@ Author=%@",name,author];
}
Run Code Online (Sandbox Code Playgroud)


tea*_*bot 24

您可以覆盖NSObject的描述方法:

- (NSString *)description
Run Code Online (Sandbox Code Playgroud)

关于日志记录的主题,我推荐这篇博文,以便更好地登录Objective-C.

  • 这不是一个静态的方法吗?我希望这可以操作对象而不是类.例如,如果我有一个"Photo"类,其字段为"name"和"author",我希望NSLog打印这些字段,因为它们是在对象中分配的. (4认同)
  • 是的 - 很好看 - 我按错了钥匙.在证明阅读我的答案时,我显然应该多加注意.值得庆幸的是有人关注球:-) (2认同)

Mad*_*ane 13

您可以使用两种功能.

- (NSString*)description
Run Code Online (Sandbox Code Playgroud)

当您将对象作为IE的参数时,将显示此参数NSLog.其他描述功能是:

- (NSString*)debugDescription
Run Code Online (Sandbox Code Playgroud)

po anInstanceOfYourClass在调试命令窗口中执行此操作时将调用此方法.如果你的类没有debugDescription函数,那么description就会被调用.

请注意,基类NSObject确实已description实现,但它相当简单:它只显示对象的地址.这就是为什么我建议您description在任何想要获取信息的类中实现,特别是如果您description在代码中使用该方法.如果您description在代码中使用,我建议您也实现debugDescription,也要debugDescription更详细.