今天讲Objective-C的类方法,类方法和类属性在前面写一个“+”号,和instance method方法的“-”对应。具体如下:
Objective-C Classes Are also Objects
In Objective-C, a class is itself an object with an opaque type called Class. Classes can’t have properties defined using the declaration syntax shown earlier for instances, but they can receive messages.
The typical use for a class method is as a factory method, which is an alternative to the object allocation and initialization procedure described in Objects Are Created Dynamically. The NSString class, for example, has a variety of factory methods available
to create either an empty string object, or a string object initialized with specific characters, including:
+ (id)string;
+ (id)stringWithString:(NSString *)aString;
+ (id)stringWithFormat:(NSString *)format, …;
+ (id)stringWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error;
+ (id)stringWithCString:(const char *)cString encoding:(NSStringEncoding)enc;As shown in these examples, class methods are denoted by the use of a + sign, which differentiates them from instance methods using a - sign.
Class method prototypes may be included in a class interface, just like instance method prototypes. Class methods are implemented in the same way as instance methods, inside the @implementation block for the class.
Objective-C 类方法详解
本文介绍了Objective-C中类方法的基本概念及其用法。类方法使用加号标记,并且可以作为工厂方法来替代对象的分配与初始化过程。文章还列举了NSString类中的多个类方法实例。
233

被折叠的 条评论
为什么被折叠?



