Objective-C中的alloc,init和new [英] alloc, init, and new in Objective-C

查看:112
本文介绍了Objective-C中的alloc,init和new的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于iPhone编程的一本书实例化了这样的类:

One book for about iPhone programming instantiates classes like this:

[[Class alloc] init]

另一本有关Objective-C的书是这样的:

Another book about Objective-C does it like this:

[Class new]

有什么区别?

推荐答案

最初在Objective-C中,对象是使用new创建的.随着OpenStep/Cocoa框架的发展,设计人员提出了这样的观点,即为对象分配内存和初始化其属性是单独的关注点,因此应该是单独的方法(例如,对象可能分配在特定的内存区域中).因此,对象创建的alloc-init样式受到青睐.

Originally in Objective-C, objects were created with new. As the OpenStep/Cocoa framework evolved, the designers developed the opinion that allocating the memory for an object and initializing its attributes were separate concerns and thus should be separate methods (for example, an object might be allocated in a specific memory zone). So the alloc-init style of object creation came into favor.

基本上,new是旧的并且几乎不被淘汰-因此您会看到Cocoa类具有很多init方法,但是几乎没有任何自定义的new方法.

Basically, new is old and almost-but-not-quite deprecated — thus you'll see that Cocoa classes have a lot of init methods but almost never any custom new methods.

这篇关于Objective-C中的alloc,init和new的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆