3 回答

TA貢獻1803條經(jīng)驗 獲得超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".
還有另一個問題涉及類方法和實例方法之間的區(qū)別。

TA貢獻1772條經(jīng)驗 獲得超8個贊
(+)代表類方法,(-)代表實例方法,
(+)類方法:-
是聲明為靜態(tài)的方法。可以在不創(chuàng)建類實例的情況下調(diào)用該方法。類方法只能對類成員操作,而不能對實例成員操作,因為類方法不知道實例成員。除非在該類的實例上調(diào)用它們,否則也不能從該類方法內(nèi)調(diào)用該類的實例方法。
(-)實例方法:-
另一方面,需要先存在該類的實例,然后才能調(diào)用它們,因此需要使用new關(guān)鍵字創(chuàng)建一個類的實例。實例方法在類的特定實例上運行。實例方法未聲明為靜態(tài)。
如何創(chuàng)建?
@interface CustomClass : NSObject
+ (void)classMethod;
- (void)instanceMethod;
@end
如何使用?
[CustomClass classMethod];
CustomClass *classObject = [[CustomClass alloc] init];
[classObject instanceMethod];
- 3 回答
- 0 關(guān)注
- 598 瀏覽
添加回答
舉報