object-c学习笔记:new vs alloc init

转载自:http://www.cnblogs.com/ulihj/archive/2011/01/15/1936342.html

在object-c基础教程这本书里老是可以看见类似下面这种代码,我这小菜鸟就纳闷了,啥区别啊,看上去都一样么。网上找了找,找到一些说法,这里先摘出来。
    someClass* object = [someClass new];
or
    someClass* object = [[someClass alloc] init];

其实是一样的,某位老兄是这样说的,new在内部调用的alloc和init,
Actually "new" is not a keyword in Objective-C, but NSObject implements a class method "new" which simply calls "alloc" and "init".

既然一样干嘛有两个,吃饱了那个啥来着。。
The new method actually comes from NeXT days. Back then, there was no two phase initialization, it was just a single new method.  They soon realized that a two phase approach could have advantages, and introduced alloc. new was kinda deprecated, but kept in for backwards compatibility. It is exactly the same as alloc-init.  Use 'new' if it suits. One shortcoming is that it only works with the basic 'init' initializer, and will not work with other initializers (eg initWithString:).
背景说明,new是较为老式的写法,后来发现只有一个new不好使,才引入了alloc和init这种写法,保留new一是向后兼容,二是很多时候是一种更简单的写法。至于alloc这种写法可以变出这样的花来,

Frequently, you are going to need to pass arguments to init and so you will be using a different method, such as [[SomeObject alloc] initWithString: @"Foo"]. If you're used to writing this, you get in the habit of doing it this way and so [[SomeObject alloc] init] may come more naturally that [SomeObject new].
恩,确实如果不需要用其他的init函数,比如initWithString, 用new的方法,毫无疑问是更加方便的。

再来个据说是来源比较靠谱的说法:
There was a very long thread on this same subject (alloc/init vs. new) on the cocoa-dev mailing list this week (search for "[Foo new] vs [[Foo alloc] init]"). Unfortunately the documentation is not crystal clear on this, but Bill Bumgarner (an Apple Engineer) confirmed that new is implemented as allocWithZone/alloc followed by init back at least to the beginning of OS X. So the answer is, use whichever you prefer. The current vogue in Cocoa programming is to use alloc/init because it makes the intended behavior explicit.
好吧,似乎只有显示调用更加容易理解这一个区别了,总之一句话,爱谁谁。

这位兄弟来了个总结性发言,姑且咱先信了他,
    * new doesn't support custom initializers (like initWithString)
    * alloc-init is more explicit than new
General opinion seems to be that you should use whatever you're comfortable with.

以上的说法都来自http://macresearch.org/difference-between-alloc-init-and-new , 有兴趣的看看把。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值