方法C旁边的加号和减号是什么意思?

时间:2010-01-19 21:37:07

标签: objective-c syntax method-declaration

我在目标c和xcode中都很新。我想知道方法定义旁边的+-符号是什么意思。

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

4 个答案:

答案 0 :(得分:217)

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

E.g。

// 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".

another question dealing with the difference between class and instance methods

答案 1 :(得分:40)

  

(+)表示类方法,( - )表示方法,

(+)班级方法: -

是声明为静态的方法。可以在不创建类的实例的情况下调用该方法。类方法只能在类成员上操作,而不能在实例成员上操作,因为类方法不知道实例成员。除非在该类的实例上调用它们,否则也不能从类方法中调用类的实例方法。

( - )实例方法: -

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

  

如何创作?

@interface CustomClass : NSObject

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

@end
  

如何使用?

[CustomClass classMethod];

CustomClass *classObject = [[CustomClass alloc] init];
[classObject instanceMethod];

答案 2 :(得分:17)

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

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

有关详细信息,请参阅Language Specification

答案 3 :(得分: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];

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

然后调用实例方法:

[myInstance instanceMethod]

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

NSNumber *myNumber = [NSNumber numberWithInt:123];

正在调用&#39; numberWithInt&#39; NSNumber类的类方法,它是一个&#39;工厂&#39;方法(即为您提供&#39;现成的对象实例的方法)。

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

NSString * myStringInstance = @&#34; abc&#34;;