Cocoa 哪种方式创建对象?例如NSArray

来源:互联网 发布:民用枪持枪证 知乎 编辑:程序博客网 时间:2024/06/12 22:45

《programming is iOS4》有一段写到:

Many classes provide the programmer with two equivalent ways to obtain an object: either an autoreleased object or an object that you create yourself withalloc and some form of init. So, for example, NSArray supplies both the class method arrayWith- Objects: and the instance method initWithObjects:. Which should you use? On the whole, Apple would prefer you to lean towardinitWithObjects:. In general, where you can generate an object withalloc and some form of init, they’d like you to do so. That way, you are in charge of releasing the object. This policy will prevent your objects from hanging around in the autorelease pool and will keep your use of memory as low as possible.


大致内容是,一般Cocoa对象都提供两种方式创建,如NSArray提供 arrayWith- Objects 和 initWithObjects两种。总体来说,苹果建议使用第二种,因为可以手动管理对象的内存释放。第一种类方法创建,其实是把对象放入autorelease pool ,在适当的时候释放,这样的话容易造成内存升高。

原创粉丝点击