2010-08-25 52 views
0

我看到UIColor類可以像這樣調用變量[UIColor redColor]; 我怎樣才能寫我的班級做同樣的事情?此外,我可以有一種方法只適用於類,例如,像這樣:Objective C語法問題

[MyClass callingMyMethod];

謝謝。

回答

2

是。僅定義方法時使用+代替-

+ (void)callingMyMethod 
{ 
    ... 
} 
0

您必須創建一個類方法。類的方法被定義像實例的方法,但有一個+代替-

@interface MyClass : NSObject 
+ (id)classMethod; 
- (id)instanceMethod; 
@end 

@implementation MyClass 

+ (id)classMethod 
{ 
    return self; // The class object 
} 

- (id)instanceMethod 
{ 
    return self; // An instance of the class 
} 

注意,一個類的方法中,所述self變量將引用類,而不是類的一個實例。

0

是的,它們是呼叫類消息。定義消息時使用+而不是-

像這樣:

@interface MyClass : NSObject 
{ 

} 

+ (void) callingMyMethod; 
0

使用+代替-。這被稱爲類方法,用於初始化和返回對象。

@interface SomeClass : NSObject 
+ (id)callingMyMethod; 
- (id)otherMethod; 
@end 

@implementation SomeClass 

+ (id)callingMyMethod 
{ 
    return self; // The class object 
} 

- (id)otherMethod 
{ 
    return self; // An instance of the class 
}