ios developer tiny share-20160823

本文讲解了Objective-C中带有参数的初始化方法initWithXX,如initWithInt,并介绍了如何使用这些方法来创建并初始化对象。此外,还探讨了工厂方法作为分配和初始化过程的一种替代方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值