覆盖可可中的描述或字符串值?
我想要 Cocoa 中的对象有一个描述性字符串。我正在考虑重写描述方法或 stringValue 方法。哪个更可取,为什么?我能找到的唯一指南是在这里< /a> 说明
不鼓励您覆盖描述。
这确实是您的建议吗?还有其他首选覆盖点吗?
I want to have an descriptive string for an object in Cocoa. I'm thinking about overriding either the description method or the stringValue method. Which is preferable and why? The only guideline I could find was in here stating
You are discouraged from overriding description.
Is this indeed what you would suggest? Any other preferred overrride point?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我个人在我创建的几乎所有子类中都重写了
description
。我想,就像 Tom Duckering 在他的评论中所写的那样,您的引用仅适用于托管对象。I personally override
description
in virtually all subclasses I create. I guess, like Tom Duckering writes in his comment, that your quote only applies to Managed Objects.description
是正确的方法,这就是所谓的提供对象的字符串表示形式。我相信 Hillegass 的书中也建议了这一点。
description
is the way to go, that's what it's called to supply string representation of an object.I believe suggested by Hillegass' book as well.
从另一个方向回答您的问题,
stringValue
是完全不同的东西 - 它不描述接收器,它是接收器的属性。您的自定义description
甚至可能包含stringValue
,或者它的摘录(如果它很长)。一个关键的区别是,
stringValue
通常是一个可变属性(例如,参见 NSControl 的属性),而description
始终是一个不可变属性,根据需要计算。To answer your question from the other direction,
stringValue
is something altogether different—it doesn't describe the receiver, it's a property of it. Your customdescription
may even include thestringValue
, or an excerpt of it if it's long.A key difference is that
stringValue
is often a mutable property (see, for example, that of NSControl), whereasdescription
is always an immutable property, computed upon demand.您还可以覆盖调试器调用的 [NSObject debugDescription]。这就是在调试器中使用“打印到控制台”时所说的。您也可以直接在 NSLog 中调用它。
默认情况下,在大多数类中,
debugDescription
仅调用description
,但您可以让它们返回单独的字符串。这是加载带有详细信息的输出的好地方。类别是放置自定义类和现有类方法的好地方。这特别有用,因为您可以在调试版本中包含该类别,但在发布版本中将其排除。如果类别不存在,代码将调用默认类方法。
我有一个 UIView 调试类别,可以转储我能想到的每个属性。如果我遇到了严重的错误,我只需包含该类别,然后我就可以在调试器控制台中看到有关每个视图的所有内容。
You can also override [NSObject debugDescription] which is called by the debugger. It's what is called when use "print to console" in the debugger. You can also call it directly in a NSLog.
By default in most classes
debugDescription
just callsdescription
but you can make them return separate strings. It's a good place to load up the output with details.Categories are a good place to park the method for both your custom classes and existing classes. This is especially useful because you can include the category in a debug build but exclude it in the release. If the category is not present, the code calls the default class method instead.
I have a debugging category for UIView that dumps out every attribute I could think of. If I hit a nasty bug I just include the category and then I can see everything about every view right in the debugger console.