object-c学习笔记:new vs alloc init
在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 , 有兴趣的看看把。