如何为类编写正确的描述方法?
我已经实施了
- (NSString *)description {
NSString *descriptionString = [NSString stringWithFormat:@"Name: %@ \n Address: %@ \n", self.name, self.address];
return descriptionString;
}
如果我在我的对象上调用描述,那么Evrey就可以了。但是如果我有一个对象数组并且我在其上调用描述,我得到:
“姓名:Alex \ n地址:某地址\ n”,
我想得到的是
“姓名:Alex
地址:某地址“
答案 0 :(得分:18)
此外,您可以使用回车\r
,它也将以新行结束(即使在NSArray描述中)
答案 1 :(得分:12)
我在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]);
输出结果是:
FontDescription:font-family:“Helvetica”; font-weight:normal; font-style:normal; font-size:18px
FontsArrayDescription:(
"<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;
}
输出将是:
“姓名:Alex;地址:某地址;”
对象是自我。
objecsArrayDescription:(
"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;"
)
对于一组对象。