上节我们讲Objective-C的init方法,这节我们讲initWithXX方法,如initWithInt,实现带有参数的初始化方法。另外,我们讲一下工厂方法实现初始化。
Initializer Methods Can Take Arguments
Some objects need to be initialized with required values. An NSNumber object, for example, must be created with the numeric value it needs to represent.
The NSNumber class defines several initializers, including:
- (id)initWithBool:(BOOL)value;
- (id)initWithFloat:(float)value;
- (id)initWithInt:(int)value;
- (id)initWithLong:(long)value;Initialization methods with arguments are called in just the same way as plain init methods—an NSNumber object is allocated and initialized like this:
NSNumber *magicNumber = [[NSNumber alloc] initWithInt:42];
As mentioned in the previous chapter, a class can also define factory methods. Factory methods offer an alternative to the traditional alloc] init] process, without the need to nest two methods.
The NSNumber class defines several class factory methods to match its initializers, including:
+ (NSNumber *)numberWithBool:(BOOL)value;
+ (NSNumber *)numberWithFloat:(float)value;
+ (NSNumber *)numberWithInt:(int)value;
+ (NSNumber *)numberWithLong:(long)value;A factory method is used like this:
NSNumber *magicNumber = [NSNumber numberWithInt:42];This is effectively the same as the previous example using alloc] initWithInt:]. Class factory methods usually just call straight through to alloc and the relevant init method, and are provided for convenience.
本文讲解了Objective-C中带有参数的初始化方法initWithXX,如initWithInt,并介绍了如何使用这些方法来创建并初始化对象。此外,还探讨了工厂方法作为分配和初始化过程的一种替代方案。
233

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



