我在目标c和xcode中都很新。我想知道方法定义旁边的+
和-
标志是什么意思。
- (void)loadPluginsAtPath:(NSString*)pluginPath errors:(NSArray **)errors;
+
用于类方法,-
用于实例方法。
EG
// 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。
(+)用于类方法和( - )用于例如方法,
(+)班级方法: -
是声明为静态的方法。可以在不创建类的实例的情况下调用该方法。类方法只能在类成员上操作,而不能在实例成员上操作,因为类方法不知道实例成员。除非在该类的实例上调用类,否则也不能从类方法中调用类的实例方法。
( - )实例方法: -
另一方面,在调用类之前需要该类的实例存在,因此需要使用new关键字创建类的实例。实例方法对特定的类实例进行操作。实例方法未声明为静态。
怎么创造?
@interface CustomClass : NSObject
+ (void)classMethod;
- (void)instanceMethod;
@end
如何使用?
[CustomClass classMethod];
CustomClass *classObject = [[CustomClass alloc] init];
[classObject instanceMethod];
+方法是类方法 - 即无法访问实例属性的方法。用于不需要访问实例变量的类的alloc或helper方法等方法
- 方法是实例方法 - 与对象的单个实例相关。通常用于类的大多数方法。
有关更多详细信息,请参阅Language Specification。
苹果公司对此的明确解释是在“方法和消息”部分下面的:
在信中:
(可以在没有实例化类的实例的情况下调用方法)。所以你这样称呼它:
[className classMethod];
您需要首先实例化一个对象,然后您可以调用该对象上的方法)。您可以手动实例化这样的对象:
SomeClass* myInstance = [[SomeClass alloc] init];
(这实际上是为对象分配内存空间然后在该空间中初始化对象 - 过度简化但是考虑它的好方法。你可以单独分配和初始化对象但从不这样做 - 它可能导致与指针相关的讨厌问题和内存管理)
然后调用实例方法:
[myInstance instanceMethod]
在Objective C中获取对象实例的另一种方法是这样的:
NSNumber *myNumber = [NSNumber numberWithInt:123];
它调用NSNumber类的'numberWithInt'类方法,这是一种'工厂'方法(即为您提供对象的'现成实例'的方法)。
Objective C还允许使用特殊语法直接创建某些对象实例,就像这样的字符串一样:
NSString * myStringInstance = @“abc”;