第17条:实现description方法
覆写description方法
调试程序时,需要打印并查看对象信息,这时候可以借助description方法和debugDescription方法。其中debugDescription方法是用于调试用的。
覆写description方法并将描述对象的字符串返回即可。
如:
EOCPerson类
/* EOCPerson头文件 */
#import <Foundation/Foundation.h>
@interface EOCPerson : NSObject
@property(nonatomic ,copy, readonly) NSString *firstName;
@property(nonatomic ,copy, readonly) NSString *lastName;
- (id)initWithFirstName:(NSString *)firstName andLastName:(NSString *)lastName;
@end
/* EOCPerson实现文件 */
#import "EOCPerson.h"
@implementation EOCPerson
- (id)initWithFirstName:(NSString *)firstName andLastName:(NSString *)lastName{
if (self = [super init]) {
_firstName = [firstName copy];
_lastName = [lastName copy];
}
return self;
}
// 覆写description方法
- (NSString *)description{
return [NSString stringWithFormat:@"%@ %@", _firstName, _lastName];
}
// 覆写debugDescription方法,用于调试
- (NSString *)debugDescription{
return [NSString stringWithFormat:@"<%@: %p, \"%@ %@\">", [self class], self, _firstName, _lastName];
}
EOCLocation类
/* EOCLocation头文件 */
#import <Foundation/Foundation.h>
@interface EOCLocation : NSObject
@property(nonatomic ,copy, readonly) NSString *title;
@property(nonatomic ,assign, readonly) float latitude; // 纬度
@property(nonatomic ,assign, readonly) float longitude; // 经度
- (id)initWithTitle:(NSString *)title
latitude:(float)latitude
longitude:(float)longitude;
@end
/* EOCLocation实现文件 */
#import "EOCLocation.h"
@implementation EOCLocation
- (id)initWithTitle:(NSString *)title latitude:(float)latitude longitude:(float)longitude{
if (self = [super init]) {
_title = [title copy];
_latitude = latitude;
_longitude = longitude;
}
return self;
}
// 覆写description,且将属性信息包装到字典中
- (NSString *)description{
return [NSString stringWithFormat:@"%@",
@{@"title": _title,
@"latitude": @(_latitude),
@"longitude": @(_longitude)
}
];
}
// 覆写debugDescription,且将属性信息包装到字典中,用于调试
- (NSString *)debugDescription{
return [NSString stringWithFormat:@"<%@, %p, %@>",
[self class],
self,
@{@"title": _title,
@"latitude": @(_latitude),
@"longitude": @(_longitude)
}
];
}
@end
main函数
#import <Foundation/Foundation.h>
#import "EOCPerson.h"
#import "EOCLocation.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
EOCPerson *person = [[EOCPerson alloc] initWithFirstName:@"Bob" andLastName:@"Smith"];
NSLog(@"person = %@", person);
EOCLocation *location = [[EOCLocation alloc] initWithTitle:@"London" latitude:51.506 longitude:0];
NSLog(@"location = %@", location);
}
return 0;
}
输出结果:
要点
- 实现description方法返回一个有意义的字符串,用以描述该实例。
- 若想在调试时打印出更详尽的对象描述信息,则应实现debugDescription方法。