17、实现description方法

首先description方法是定义在NSObject协议里的,然后NSObjectNSProxy俩“根类”都遵循了该协议,并有默认实现:打印类名和内存地址(如:<Person: 0x7f9a1600600>)。

  • NSLog+%@打印时调用的是description方法

  • 程序运行打断点时,在调试控制台输入LLDBpo命令,调用的是debugDescription方法

可以实现如下:

- (NSString *)description {
  return [NSString stringWithFormat:@"%@ %@", _firstName, _lastName];
} // Bob Smith
- (NSString *)debugDescription {
  return [NSString stringWithFormat:@"<%@: %p,\" %@ %@\">", [self class], self, _firstName, _lastName];
} // (Person *) $1 = 0x07117fb0 <Person: 0x7117fb0, "Bob Smith">

要点:

  • 实现description方法返回一个有意义的字符串,用以描述该实例

  • 若想在调试时打印出更详尽的对象描述信息,则应实现debugDescription方法

Last updated

Was this helpful?