// 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".
4 回答
()用于类方法和( - )用于实例方法,
()类方法: -
是被声明为静态的方法 . 可以在不创建类的实例的情况下调用该方法 . 类方法只能在类成员上操作,而不能在实例成员上操作,因为类方法不知道实例成员 . 除非在该类的实例上调用类,否则也不能从类方法中调用类的实例方法 .
( - )实例方法: -
另一方面,在调用类之前需要该类的实例存在,因此需要使用new关键字创建类的实例 . 实例方法对特定的类实例进行操作 . 实例方法未声明为静态 .
方法是类方法 - 即无法访问实例属性的方法 . 用于不需要访问实例变量的类的alloc或helper方法等方法
有关详细信息,请参阅Language Specification .
+
用于类方法,-
用于实例方法 .例如 .
有another question dealing with the difference between class and instance methods .
苹果公司对此的明确解释是在“方法和消息”部分下面的:
https://developer.apple.com/library/mac/referencelibrary/GettingStarted/RoadMapOSX/books/WriteObjective-CCode/WriteObjective-CCode/WriteObjective-CCode.html
简单来说:
表示'类方法'
(可以在没有实例化类的实例的情况下调用方法) . 所以你这样称呼它:
- 表示'实例方法'
您需要首先实例化一个对象,然后您可以在该对象上调用该方法) . 您可以手动实例化这样的对象:
(这实际上为对象分配了内存空间,然后在该空间中初始化对象 - 过度简化但是考虑它的好方法. You can alloc and init the object seperately but never do this - 它可能导致与指针和内存管理相关的讨厌问题)
然后调用实例方法:
在Objective C中获取对象实例的另一种方法是这样的:
它调用NSNumber类的'numberWithInt'类方法,这是一个'factory'方法(即为您提供对象的'ready made instance'的方法) .
Objective C还允许使用特殊语法直接创建某些对象实例,就像这样的字符串一样:
NSString * myStringInstance = @“abc”;