2013-02-03 31 views
-3

可能重複:
Difference between 「+」 and 「-」 before function name in Objective-C關於Objective-C中的「+ className」?

什麼在Objective-C確實有關 「+的className」 的意味? + className是一個類方法名稱。 非常感謝。

+1

在什麼情況下?舉一個你看到它被使用的地方的例子。 –

+0

你的意思是類方法? – TheAmateurProgrammer

+0

http://developer.apple.com/library/ios/#documentation/general/Conceptual/CocoaEncyclopedia/ClassClusters/ClassClusters.html – CocoaUser

回答

-2

docs

真子類:一個例子 假設您想要創建的NSArray一個子類,名爲MonthArray,返回給定了索引位置的月份名稱。但是,MonthArray對象實際上不會將月份名稱數組存儲爲實例變量。相反,返回給定索引位置(objectAtIndex:)的名稱的方法將返回常量字符串。因此,無論應用程序中存在多少個MonthArray對象,只會分配十二個字符串對象。

的MonthArray類被聲明爲:

#import <foundation/foundation.h> 
@interface MonthArray : NSArray 

+ (id)monthArray; 
- (unsigned)count; 
- (id)objectAtIndex:(unsigned)index; 

@end 

注意,MonthArray類未聲明的init...方法,因爲它沒有實例變量初始化。如上所述,countobjectAtIndex:方法僅覆蓋繼承的原始方法。

的MonthArray類的實現看起來是這樣的:

#import "MonthArray.h" 

@implementation MonthArray 

static MonthArray *sharedMonthArray = nil; 
static NSString *months[] = { @"January", @"February", @"March", 
    @"April", @"May", @"June", @"July", @"August", @"September", 
    @"October", @"November", @"December" }; 

+ (id)monthArray 
{ 
    if (!sharedMonthArray) { 
     sharedMonthArray = [[MonthArray alloc] init]; 
    } 
    return sharedMonthArray; 
} 

- (unsigned)count 
{ 
    return 12; 
} 

- (id)objectAtIndex:(unsigned)index 
{ 
    if (index >= [self count]) 
     [NSException raise:NSRangeException format:@"***%s: index 
      (%d) beyond bounds (%d)", sel_getName(_cmd), index, 
      [self count] - 1]; 
    else 
     return months[index]; 
} 

@end 

因爲MonthArray覆蓋繼承原始的方法,它繼承將正常工作而不被重寫衍生方法。 NSArraylastObject,containsObject:,sortedArrayUsingSelector:,objectEnumerator和其他方法對MonthArray對象沒有問題。

+2

我看不到「+ className」與類別 –

+0

的關係你的意思是像這樣的'+(ClassName *)Instance' – Flexicoder

+0

不,請看看 - > http://developer.apple。com/library/ios/#documentation/general/Conceptual/CocoaEncyclopedia/ClassClusters/ClassClusters.html – CocoaUser

2

Class Cluster文件所引用,+的className ...僅僅是各種類的方法可用來創建類集羣,例如實例的佔位符numberWithCharnumberWithInt,...對於NSNumber

這與NSObject-className實例方法無關。