类方法和实例方法的区别
类方法和实例方法有什么区别。为什么我们需要单独使用它们? 有人可以解释一下吗?
类和实例方法
• 实例响应实例方法
- (id)init;
- (float)height;
- (void)walk;
• 类响应类方法
+ (id)alloc;
+ (id)person;
+ (Person *)sharedPerson;
Taimur
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
实例方法仅在类的实例上可用,而类方法不需要实例但在类上可用。
类方法由
+
表示,而实例方法在其返回类型之前由-
表示。我们以 NSObject 为例。
NSObject
有一个名为+ (id)alloc
的类方法。 alloc 方法用于分配类的实例。显然 alloc 必须是一个类方法,因为如果它是一个实例方法,那么您将从哪里获得“根”实例?另一方面,
- (id)init
是一个实例方法,因为它初始化实例的状态。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.一个例子:
Human
->类
你
->实例
人类
可以消灭
,你
不能。你
可以喝可乐
,人类
不能。Instance
方法仅适用于个体,而
Class
方法适用于具有相同可识别特征的整个群体。这是一个与许多、个人与整个社会之间的区别。
[SomeClass alloc]
表示该类的新实例诞生就像你出生一样,
init
适用于一个Instance
,就像你的父母给你起名字,养活你,送你上学,这样你就有了生活的技能这个社会。An example:
Human
->Class
You
->Instance
Human
couldextinguish
,you
cannot.You
coulddrink 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 bornjust like You are given birth,
init
applies to anInstance
, like your parents give you a name, feed you and send you to school, so you have skills to live in this society.