在Objective c中,哪个名称的方法与类名相同?

时间:2015-03-07 18:49:23

标签: objective-c classname

抱歉,我在https://developer.apple.com/library/ios/documentation/General/Conceptual/CocoaEncyclopedia/ClassClusters/ClassClusters.html中看到了一段代码,我不明白在Objective c中与类名同名的方法有什么用?

#import <foundation/foundation.h>

@interface MonthArray : NSArray

{
}



+ monthArray; // what is this function, a constructor?

- (unsigned)count;

- (id)objectAtIndex:(unsigned)index;



@end

使用与类名相同的名称来定义函数是否有任何特殊含义?构造函数?

2 个答案:

答案 0 :(得分:1)

与类同名的类方法通常是工厂方法。这是一种常见的惯例,但是语言并不要求或强制执行。

例如[NSArray array]返回一个空数组。它就像[[NSArray alloc] init]

方法名称旁边的+使它成为一个类方法,这意味着您可以直接在类上调用它:[MonthArray monthArray]

答案 1 :(得分:1)

这是一种允许更易读的代码和便利的约定。如果您想在自己的代码中构建此行为,则可以执行以下操作...

// DogClass.h
@interface DogClass : NSObject

+ (instancetype)dog;

- (instancetype)initWithDogName:(NSString *)name ownerName:(NSString *)ownerName birthYear:(NSNumber *)birthYear breed:(NSString *)breed;

@end

// DogClass.m
@implementation DogClass

+ (instancetype)dog {
DogClass *aDog = [[DogClass alloc] initWithDogName:@"" ownerName:@"" birthYear:@(0) breed:@""];
return aDog;
}

- (instancetype)initWithDogName:(NSString *)name ownerName:(NSString *)ownerName birthYear:(NSNumber *)birthYear breed:(NSString *)breed {
    if (self = [super init]) {
        self.name = name;
        self.ownerName = ownerName;
        self.birthYear = birthYear;
        self.dateAdded = [NSDate date];
        self.breed = breed;
    }
    return self;
}
@end

现在你可以用两种方式之一初始化DogClass,因为它们以相同的方式初始化......

DogClass = [DogClass dog]; 

DogClass = [[DogClass alloc] initWithDogName:@"" ownerName:@"" birthYear:@(0) breed:@""]