差异类和实例方法 [英] Difference Class and Instance Methods

查看:64
本文介绍了差异类和实例方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类方法和实例方法之间的区别是什么?为什么我们需要单独使用它们? 有人可以解释一下吗?

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

类和实例方法

•实例响应实例方法

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

•类响应类方法

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

Taimur

推荐答案

实例方法仅在类的实例上可用,而类方法不需要实例,但在类上可用.

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.

让我们以NSObject为例. NSObject具有一个名为+ (id)alloc的类方法. alloc方法用于分配类的实例.显然,alloc必须是一个类方法,因为如果它是一个实例方法,那么您将从何处获得根"实例?

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?

另一方面,- (id)init是一种实例方法,因为它可以初始化实例的状态.

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

这篇关于差异类和实例方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆