ios developer tiny share-20160823

来源:互联网 发布:凡古加网络 编辑:程序博客网 时间:2024/06/05 16:56

上节我们讲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];


Class Factory Methods Are an Alternative to Allocation and Initialization
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.

0 0
原创粉丝点击