可能重複:
Difference between 「+」 and 「-」 before function name in Objective-C關於Objective-C中的「+ className」?
什麼在Objective-C確實有關 「+的className」 的意味? + className是一個類方法名稱。 非常感謝。
可能重複:
Difference between 「+」 and 「-」 before function name in Objective-C關於Objective-C中的「+ className」?
什麼在Objective-C確實有關 「+的className」 的意味? + className是一個類方法名稱。 非常感謝。
從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...
方法,因爲它沒有實例變量初始化。如上所述,count
和objectAtIndex:
方法僅覆蓋繼承的原始方法。的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覆蓋繼承原始的方法,它繼承將正常工作而不被重寫衍生方法。
NSArray
的lastObject
,containsObject:
,sortedArrayUsingSelector:
,objectEnumerator
和其他方法對MonthArray對象沒有問題。
我看不到「+ className」與類別 –
的關係你的意思是像這樣的'+(ClassName *)Instance' – Flexicoder
不,請看看 - > http://developer.apple。com/library/ios/#documentation/general/Conceptual/CocoaEncyclopedia/ClassClusters/ClassClusters.html – CocoaUser
在Class Cluster文件所引用,+的className ...僅僅是各種類的方法可用來創建類集羣,例如實例的佔位符numberWithChar
,numberWithInt
,...對於NSNumber
。
這與NSObject
的-className
實例方法無關。
在什麼情況下?舉一個你看到它被使用的地方的例子。 –
你的意思是類方法? – TheAmateurProgrammer
http://developer.apple.com/library/ios/#documentation/general/Conceptual/CocoaEncyclopedia/ClassClusters/ClassClusters.html – CocoaUser