类和实例方法有什么区别? [英] What is the difference between class and instance methods?

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

问题描述

类方法和实例方法有什么区别?

实例方法是访问器(getter和setter)而类方法是几乎所有其他东西吗?

像其他大多数答案所说的那样,实例方法使用类的实例,而类方法只能与类名一起使用.因此,在Objective-C中对它们进行了定义:

@interface MyClass : NSObject

+ (void)aClassMethod;
- (void)anInstanceMethod;

@end

然后可以像这样使用它们:

[MyClass aClassMethod];

MyClass *object = [[MyClass alloc] init];
[object anInstanceMethod];

类方法的一些现实世界示例是许多Foundation类(例如NSString+stringWithFormat:NSArray+arrayWithArray:)上的便捷方法.实例方法将是NSArray-count方法.

What's the difference between a class method and an instance method?

Are instance methods the accessors (getters and setters) while class methods are pretty much everything else?

解决方案

Like most of the other answers have said, instance methods use an instance of a class, whereas a class method can be used with just the class name. In Objective-C they are defined thusly:

@interface MyClass : NSObject

+ (void)aClassMethod;
- (void)anInstanceMethod;

@end

They could then be used like so:

[MyClass aClassMethod];

MyClass *object = [[MyClass alloc] init];
[object anInstanceMethod];

Some real world examples of class methods are the convenience methods on many Foundation classes like NSString's +stringWithFormat: or NSArray's +arrayWithArray:. An instance method would be NSArray's -count method.

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

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