Difference Class and Instance Methods

自作多情 提交于 2019-12-21 17:17:08

问题


Whats the difference between class methods and Instance methods. Why do we need them separately? Can somebody please explain?

Class and Instance Methods

• Instances respond to instance methods

 - (id)init;
 - (float)height;
 - (void)walk;

• Classes respond to class methods

 + (id)alloc;
 + (id)person;
 + (Person *)sharedPerson;

Taimur


回答1:


An instance method is only available on an instance of the class, while a class method does not need an instance but is available on the class.

Class Methods are denoted by a + while instance methods are denoted by a - before their return type.

Let's take NSObject for example. NSObject has a class method named + (id)alloc. The alloc method is used to allocate an instance of the class. Obviously alloc must be a class method because if it was an instance method, where would you get the "root" instance from?

On the other hand - (id)init is an instance method because it initializes the state of an instance.




回答2:


An example:

Human -> Class You -> Instance

Human could extinguish, you cannot. You could drink a Coke, Human cannot.

Instance method is only applied to individuals,

While Class method is applied to the whole group with the same identifiable features.

It's the difference between one and many, individual and the whole society.

[SomeClass alloc] means a new instance of the class is born just like You are given birth,

init applies to an Instance, like your parents give you a name, feed you and send you to school, so you have skills to live in this society.




回答3:


  1. Use Static variables
  2. Represent by '+' symbol
  3. Can be called directly with class without creating instance of a class
  4. Self in class method represent class itself however self in instance method represents that particular instance of a class.


来源:https://stackoverflow.com/questions/3245174/difference-class-and-instance-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!