给自定义类加类方法

在Objective-C中,你可以向类或对象发送消息来完成某件事。如果你想要你的自定义类能够回应某消息,就需要首先编写一个类方法。

类方法以+号开头。例如:

+(void)writeDescriptionToLogWithThisDate:(NSDate *)date;

类的实现中这么写:

+(void)writeDescriptionToLogWithThisDate:(NSDate *)date{
        NSLog(@"Today's date is %@ and this class represents a car", date);
}

使用此类方法:

只需向该类发送一个消息,无需先实例化一个对象

[Car writeDescriptionToLogWithThisDate:[NSDate date]];

猜你喜欢

转载自zsjg13.iteye.com/blog/2258968
今日推荐