如何为类编写正确的描述方法?
我已经实施
- (NSString *)description {
NSString *descriptionString = [NSString stringWithFormat:@"Name: %@ n Address: %@ n", self.name, self.address];
return descriptionString;
}
如果我调用对象的描述,埃弗里的事情就可以了。但如果我有一个对象数组,我调用它的描述,我会得到:
"姓名:Alex地址:某个地址",
我想要的是
"姓名:Alex
地址:一些地址"
此外,您还可以使用回车r
,它也将出现在新行中(甚至在NSArray描述中)
我在iOS框架中做了更多的挖掘,我观察到iOS sdk描述的默认行为不是放置"\n",而是放置";"。
示例:
UIFont *font = [UIFont systemFontOfSize:18];
NSLog(@"FontDescription:%@",[font description]);
NSMutableArray *fontsArray = [NSMutableArray arrayWithCapacity:0];
for(int index = 0; index < 10; index++) {
[fontsArray addObject:font];
}
NSLog(@"FontsArrayDescription:%@",[fontsArray description]);
结果是:
字体描述:字体家族:"Helvetica";字体重量:正常;字体样式:普通;字体大小:18px
FontsArray描述:(
"<UICFFont: 0x6e2d8b0> font-family: "Helvetica"; font-weight: normal; font-style: normal; font-size: 18px", "<UICFFont: 0x6e2d8b0> font-family: "Helvetica"; font-weight: normal; font-style: normal; font-size: 18px", "<UICFFont: 0x6e2d8b0> font-family: "Helvetica"; font-weight: normal; font-style: normal; font-size: 18px", "<UICFFont: 0x6e2d8b0> font-family: "Helvetica"; font-weight: normal; font-style: normal; font-size: 18px", "<UICFFont: 0x6e2d8b0> font-family: "Helvetica"; font-weight: normal; font-style: normal; font-size: 18px", "<UICFFont: 0x6e2d8b0> font-family: "Helvetica"; font-weight: normal; font-style: normal; font-size: 18px", "<UICFFont: 0x6e2d8b0> font-family: "Helvetica"; font-weight: normal; font-style: normal; font-size: 18px", "<UICFFont: 0x6e2d8b0> font-family: "Helvetica"; font-weight: normal; font-style: normal; font-size: 18px", "<UICFFont: 0x6e2d8b0> font-family: "Helvetica"; font-weight: normal; font-style: normal; font-size: 18px", "<UICFFont: 0x6e2d8b0> font-family: "Helvetica"; font-weight: normal; font-style: normal; font-size: 18px"
)
所以我决定在课堂上使用同样的方法。
- (NSString *)description {
NSString *descriptionString = [NSString stringWithFormat:@"Name: %@; Address: %@;", self.name, self.address];
return descriptionString;
}
结果是:
"姓名:亚历克斯;地址:某个地址;"
对于对象本身。
objecsArray描述:(
"Name:Alex; Address: some address;", "Name:Alex; Address: some address;", "Name:Alex; Address: some address;", "Name:Alex; Address: some address;", "Name:Alex; Address: some address;", "Name:Alex; Address: some address;", "Name:Alex; Address: some address;", "Name:Alex; Address: some address;", "Name:Alex; Address: some address;", "Name:Alex; Address: some address;"
)
对于对象数组。