3 回答
TA貢獻1803條經驗 獲得超6個贊
+用于類方法和-實例方法。
例如
// 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".
還有另一個問題涉及類方法和實例方法之間的區別。
TA貢獻1772條經驗 獲得超8個贊
(+)代表類方法,(-)代表實例方法,
(+)類方法:-
是聲明為靜態的方法??梢栽诓粍摻悓嵗那闆r下調用該方法。類方法只能對類成員操作,而不能對實例成員操作,因為類方法不知道實例成員。除非在該類的實例上調用它們,否則也不能從該類方法內調用該類的實例方法。
(-)實例方法:-
另一方面,需要先存在該類的實例,然后才能調用它們,因此需要使用new關鍵字創建一個類的實例。實例方法在類的特定實例上運行。實例方法未聲明為靜態。
如何創建?
@interface CustomClass : NSObject
+ (void)classMethod;
- (void)instanceMethod;
@end
如何使用?
[CustomClass classMethod];
CustomClass *classObject = [[CustomClass alloc] init];
[classObject instanceMethod];
- 3 回答
- 0 關注
- 611 瀏覽
添加回答
舉報
