193

在 Objective-C 中,我想知道方法定义旁边的+和符号是什么意思。-

- (void)loadPluginsAtPath:(NSString*)pluginPath errors:(NSArray **)errors;
4

4 回答 4

237

+用于类方法,-用于实例方法。

例如

// Not actually Apple's code.
@interface NSArray : NSObject {
}
+ (NSArray *)array;
- (id)objectAtIndex:(NSUInteger)index;
@end

// somewhere else:

id myArray = [NSArray array];         // see how the message is sent to NSArray?
id obj = [myArray objectAtIndex:4];   // here the message is sent to myArray

// Btw, in production code one uses "NSArray *myArray" instead of only "id".

还有另一个问题是处理类和实例方法之间的区别

于 2010-01-19T21:39:02.813 回答
49

(+) 用于类方法,(-) 用于实例方法,

(+) 类方法:-

是声明为静态的方法。无需创建类的实例即可调用该方法。类方法只能对类成员进行操作,而不能对实例成员进行操作,因为类方法不知道实例成员。类的实例方法也不能从类方法中调用,除非它们是在该类的实例上调用的。

(-) 实例方法:-

另一方面,需要类的实例存在才能调用它们,因此需要使用 new 关键字创建类的实例。实例方法对类的特定实例进行操作。实例方法未声明为静态。

如何创作?

@interface CustomClass : NSObject

+ (void)classMethod;
- (void)instanceMethod;

@end

如何使用?

[CustomClass classMethod];

CustomClass *classObject = [[CustomClass alloc] init];
[classObject instanceMethod];
于 2013-08-02T11:06:33.147 回答
19

+ 方法是类方法 - 即无权访问实例属性的方法。用于不需要访问实例变量的类的 alloc 或辅助方法等方法

- 方法是实例方法 - 与对象的单个实例相关。通常用于类上的大多数方法。

有关详细信息,请参阅语言规范

于 2010-01-19T21:39:48.500 回答
5

Apple对此的最终解释在这里,在“方法和消息”部分下:

https://developer.apple.com/library/mac/referencelibrary/GettingStarted/RoadMapOSX/books/WriteObjective-CCode/WriteObjective-CCode/WriteObjective-CCode.html

简单来说:

+ 表示“类方法”

(可以在没有实例化类的实例的情况下调用方法)。所以你这样称呼它:

[className classMethod]; 


- 表示“实例方法”

您需要先实例化一个对象,然后才能调用该对象上的方法)。您可以像这样手动实例化一个对象:

SomeClass* myInstance = [[SomeClass alloc] init];

(这实质上是为对象分配内存空间,然后在该空间中初始化对象 - 过于简单,但考虑它的好方法。您可以单独分配和初始化对象,但永远不要这样做- 它可能导致与指针相关的讨厌问题和内存管理)

然后调用实例方法:

[myInstance instanceMethod]

在 Objective C 中获取对象实例的另一种方法是这样的:

NSNumber *myNumber = [NSNumber numberWithInt:123];

它正在调用 NSNumber 类的“numberWithInt”类方法,这是一个“工厂”方法(即一种为您提供对象的“现成实例”的方法)。

Objective C 还允许使用特殊语法直接创建某些对象实例,例如这样的字符串:

NSString *myStringInstance = @"abc";

于 2015-10-15T20:46:04.137 回答