1、问题
在Objective-C中,你可以给类或对象发消息来完成任务。如果你想要你的自定义类能够响应消息,那就需要编写一个class方法。
2、解决方案
要添加class方法,你需要在头文件中添加forward声明。class方法以+开头,还要有一个返回类型,如(void),之后是一组参数描述符,数据类型,以及参数名。class方法要在类实现文件中实现,放在@implementation关键字后面。
3、原理
下面是一个class方法的forward declaration:
+(void) writeDescriptionToLogWithThisDate:(NSDate *)date;
然后到.m文件中实现该方法:
+(void)writeDescriptionToLogWithThisDate:(NSDate *)date{
NSLog(@"Today's date is %@ and this class represents a car", date);
要使用该方法,你只需要向该Car类发一个消息,无需担心先要实例化一个对象。
[Car writeDescriptionToLogWithThisDate:[NSDate date]];
}
4、代码
Listing 1-10. Car.h
#import <Foundation/Foundation.h>
@interface Car : NSObject
@property(strong) NSString *name;
+(void)writeDescriptionToLogWithThisDate:(NSDate *)date;
@end
======================================================
Listing 1-11. Car.m
#import "Car.h"
@implementation Car
@synthesize name;
+(void)writeDescriptionToLogWithThisDate:(NSDate *)date{
NSLog(@"Today's date is %@ and this class represents a car", date);
}
@end
============================================================
Listing 1-12. main.m
#import "Car.h"
int main (int argc, const char * argv[]){
@autoreleasepool {
[Car writeDescriptionToLogWithThisDate:[NSDate date]];
}
return 0;
}
class方法就像Java中的静态方法。