如何为类编写正确的描述方法?
Posted
技术标签:
【中文标题】如何为类编写正确的描述方法?【英文标题】:How to write proper description method to a class? 【发布时间】:2012-02-19 10:56:42 【问题描述】:我已经实现了
- (NSString *)description
NSString *descriptionString = [NSString stringWithFormat:@"Name: %@ \n Address: %@ \n", self.name, self.address];
return descriptionString;
如果我在我的对象上调用描述,一切都很好。但是,如果我有一个对象数组并且我调用它的描述,我会得到:
"姓名:Alex \n 地址:某个地址\n",
我想得到的是
“姓名:亚历克斯
地址:某个地址"
【问题讨论】:
您必须遍历元素并在每个元素上调用description
。数组描述是格式化输出,可能会短路“\n”之类的东西,以保持格式一致
见http://***.com/a/1828689/971401。那里的答案可能会对您有所帮助。
【参考方案1】:
此外,您还可以使用回车符\r
,它也会在新行中结束(即使在 NSArray 描述中)
【讨论】:
优秀的答案!虽然我仍然无法让 \t 工作,所以我最终得到了“”(4 个空格)。 为我工作,谢谢【参考方案2】:我对 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";字体粗细:正常;字体样式:正常;字体大小: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;地址:某个地址;"
对于它自己的对象。
objectsArrayDescription:(
"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;"
)
对于一个对象数组。
【讨论】:
以上是关于如何为类编写正确的描述方法?的主要内容,如果未能解决你的问题,请参考以下文章