objective-c - 在Obj-C中实例方法和类方法的区别是什么?
習慣沉默
習慣沉默 2017-05-02 09:20:30
0
3
774

实例方法,即需要实例化对象调用的方法。
类方法,即类直接调用的方法。

我不明白什么场合用类方法,什么场合用实例方法。两者相比较真正的优势和劣势又是什么?

習慣沉默
習慣沉默

reply all(3)
迷茫

Class methods are generally used to provide standardized processing; instance methods are generally used to provide personalized processing (binding to specific instances).

曾经蜡笔没有小新

There should be no such thing as advantages and disadvantages.

  • If a method has the same input parameters, the output will be affected by the instance variables of different object instances. Generally, it should be written as an instance method.

  • If the input parameters are the same but are not affected by instance variables (static does not count as instance variables), you can write a class method and give it to the class to call. For example

- (NSString *)getCertainString
{
    return @"The string."
}

You can write this kind of ghost as an instance method, but not only will one be instantiated/released every time it is called, it will also affect code reading.

  • Class methods are more common in singleton mode and factory mode. This class in the singleton mode program has only one instance; the factory mode produces different instances and returns them based on the parameters.

阿神

There is no distinction between the methods, they are just for convenience of use. If you have to distinguish, the following should be considered

Disadvantages of class methods: In class methods, self represents a class, not a class object, so in a class method you cannot use self. to call attributes, nor can you call instance methods of this class.
Advantages of class methods: The call is simple, no need to create objects

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template