一本关于iPhone编程的书实例化了这样的类:
[[Class alloc] init]
Run Code Online (Sandbox Code Playgroud)
另一本关于Objective-C的书是这样的:
[Class new]
Run Code Online (Sandbox Code Playgroud)
有什么不同?
bbu*_*bum 75
+new
在字面上实现如下:
+ (id) new
{
return [[self alloc] init];
}
Run Code Online (Sandbox Code Playgroud)
没有更多,没有更少.类可能会覆盖它,但这非常不典型,有利于做类似的事情+fooWithBar:
.
Chu*_*uck 71
最初在Objective-C中,对象是用new创建的.随着OpenStep/Cocoa框架的发展,设计人员提出了这样的观点:为对象分配内存并初始化其属性是单独的问题,因此应该是单独的方法(例如,对象可能在特定的内存区域中分配).因此,对象创建的alloc-init风格受到青睐.
基本上,new是旧的,几乎没有被弃用 - 因此你会发现Cocoa类有很多init方法,但几乎从来没有任何自定义的新方法.
use*_*621 13
As already mentioned, by defaut there is no difference. But you can overwrite the new
class method. Apple's documentation has some thoughts on this.
Unlike alloc, new is sometimes re-implemented in subclasses to invoke a class-specific initialization method[...] Often new... methods will do more than just allocation and initialization.
归档时间: |
|
查看次数: |
31725 次 |
最近记录: |