从描述方法输出 iVar?
我很确定我只是错过了这里的重点并且感到困惑。谁能告诉我如何为一个对象编写一个简单的描述,该描述将其实例变量的值打印到控制台。
另外:无论如何,是否可以将信息呈现为一个块(即,如果您有 10 个 iVar,那么让它们全部一一返回将是一件痛苦的事情)
@interface CelestialBody : NSObject {
NSString *bodyName;
int bodyMass;
}
- (NSString *)description {
return (@"Name: %@ Mass: %d", bodyName, bodyMass);
}
干杯 -gary-
I am pretty sure I am just missing the point here and getting confused. Can anyone tell me how I might write a simple description for an object that will print out the value of its instance variables to the console.
Also: is there anyway to present the information as a block (i.e. if you had 10 iVars its going to be a pain getting them all to return one by one)
@interface CelestialBody : NSObject {
NSString *bodyName;
int bodyMass;
}
- (NSString *)description {
return (@"Name: %@ Mass: %d", bodyName, bodyMass);
}
cheers -gary-
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
看看这个的答案问题。代码转载如下:
Look at the answer to this question. The code is reproduced below:
正如 Jason 所写,您应该使用 stringWithFormat: 使用类似 printf 的语法来格式化字符串。
为了避免为许多类一遍又一遍地编写此内容,您可以在 NSObject 上添加一个类别,以便您轻松检查实例变量。这将导致性能不佳,但可用于调试目的。
有了这个,实现描述也是小菜一碟:
不要将此
description
添加为 NSObject 上的类别,否则最终可能会出现无限递归。As Jason wrote you should use stringWithFormat: to format strings with printf like syntax.
To avoid writing this over and over again for many classes you could add a category on NSObject that allows you to inspect instance variables easily. This will be bad performance, but works for debugging purposes.
With this in place implementing description is also a piece of cake:
Do not add this
description
as a category on NSObject, or you might end up with infinite recursions.这并不是一个坏主意,而且它几乎也是可以实现的。
That's not a bad idea what you had there, it's almost achievable too.