简体   繁体   English

建议在Objective-C中使用类方法和对象方法的最佳方法?

[英]Suggest best way to use class methods and object methods in Objective-C?

I am using both methods in my project, can you please let me know, which one is best for in which situation? 我在项目中同时使用这两种方法,请告诉我,哪种方法最适合哪种情况?

Regards, Sri 问候,斯里

Well, completely seriously, class methods should be specific to a class, and instance methods should be specific to an instance. 好吧,完全认真地讲,类方法应该特定于一个类,实例方法应该特定于一个实例。 Think about the method in question; 想想有问题的方法; does it depend on instance variables? 它取决于实例变量吗? Is it referring to a specific instance of the class in question? 它是指所讨论类的特定实例吗? Or is it more general than that? 还是比这更笼统?

Frequently, class methods are convenient ways to return instances (for example, [NSColor redColor] is a handy class method for returning a common instance of NSColor ). 通常,类方法是返回实例的便捷方法(例如[NSColor redColor]是用于返回NSColor的公共实例的便捷类方法)。 On the other hand, the instance method -greenComponent (which returns the green component of an RGB color) clearly needs to refer to a specific instance (if I asked you, "how much green is in color?" that wouldn't make sense. It's "how much green is in this color here ?" that is a reasonable question). 另一方面,实例方法-greenComponent (返回RGB颜色的绿色分量)显然需要引用特定的实例(如果我问你“多少颜色是绿色?”),这是没有意义的。是“ 这里的这种颜色有多少绿色?”这是一个合理的问题)。

You can also browse Apple's class references to get a better feel for which sorts of things are class methods (+) vs. instance methods (-). 您还可以浏览Apple的类引用,以更好地了解类方法(+)与实例方法(-)的区别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM