In Objective-C it takes two steps to create an object;in order,you must
. Allocate memory to store the new object.
. Initialize the newly allocated memory to appropriate values.
An object isn't fully functional until both steps are completed.
1、Creating and initializing objects
For objects that inherit from NSObject,memory for new objects is typically allocated by calling
the class method alloc.例如:CTRentalProperty *newRental = [CTRentalProperty alloc];
This statement uses the alloc method to reserve enough memory to store all the instance variables associated with a CTRentalProperty object.
You don't need to write your own implementation of the alloc method because the default version
inherited from NSObject is suitable.
Most objects,however,do require additional initialization once the memory has been allocated.
By convention,this initialization is achieved by calling a method named init:
CTRentalProperty *newRental = [CTRentalProperty alloc];
[newRental init];
It's even possible to perform both of these steps in a single line by nesting the message
sends as follows:
CTRentalProperty *newRental = [[CTRentalProperty alloc] init];
What do uninitialized instance variables get set to?
Unlike typical C-style memory allocation strategies,the memory returned by alloc has each
instance variable initialized to the value zero(or its equivalent:nil,NULL,NO,0.0,and so on).
这就意味着,你不必多此一举地将变量初始化为这样的值。
isConfigured may be a better instance variable name than needsConfiguration.
The code snippet that called alloc and init on separate lines has a silent but potentially
fatal flaw.Alough it may not be a problem with most classes,it's possible for init to return
an object different from the one created by alloc.
In coding terms this means you should always store the return value of init;here is a bad
example:
CTRentalProperty *newRental = [CTRentalProperty alloc];
[newRental init];
And here is a good example:
CTRentalProperty *newRental = [CTRentalProperty alloc];
newRental = [newRental init];
所以,干脆这么写CTRentalProperty *newRental = [[CTRentalProperty alloc] init];就没事了。
你可能会好奇什么情况下init可能会返回一个不同于alloc分配的那个对象。对于大多数类,这种情况
从不会发生,但是在特殊的情况下(implementing singletons,caches,or named instances,
and so on),a class developer may decide to more tightly control when objects are created,
preferring to return an existing object that's equivalent rather than initialize a new one,
for example.
It isn't always possible for an initialization method to perform its intended task.In such
cases it's common for the init method to free the memory associated with the new object and
return nil,indicating that the requested object couldn't be initialized.
If there's a chance that your initialization method may fail,you may like to explicitly
check for this condition,as demonstrated here:
CTRentalProperty newRental = [[CTRentalProperty alloc] init];
if (newRental == nil) {
NSLog(@"Failed to create new rental property");
}
An initialization method that accepts no parameters has limited practical use.Typically,
a class provides one or more specialized initialization methods.These methods are commonly
named using the form initWithXYZ:,where XYZ is replaced with a description of any additional
parameters required to properly initialize the object.
例如,将下面的方法声明添加到CTRentalProperty类的@interface部分:
- (id)initWithAddress:(NSString *)newAddress
rentalPrice:(float)newRentalPrice
andType:(PropertyType)newPropertyType;
下面是CTRentalProperty类的@implementation部分对此方法声明的实现:
- (id)initWithAddress:(NSString *)newAddress
rentalPrice:(float)newRentalPrice
andType:(PropertyType)newPropertyType
{
if ((self = [super init])) {
self.address = newAddress;
self.rentalPrice = newRentalPrice;
self.propertyType = newPropertyType;
}
return self;
}
上面的代码有些地方要解释一下:Working from right to left,it first sends the init message to
super.super is a keyword,similar to self,that enables you to send messages to the superclass.
Before you initialize any of your own instance variables,it's important to provide your
superclass a chance to initialize its own state.The object returned by the superclass's init
method is then assigned to self in case it has substituted your object for another.You then
check this value to ensure it isn't nil,
如果,你喜欢的话,也可以写成2行:
self = [super init];
if (self != nil) {
}
Because it's common to allocate an object and then want to immediately initialize it,many
classes provide convenience methods that combine the two steps into one.These class methods
are typically named after the class that contains them.A good example is NSString's
stringWithFormat: method,which allocates and initializes a new string with the contents
generated by the specified format string.
To allow users to easily create a new rental property object, add the following class
method to the CTRentalProperty class:
+ (id)rentalPropertyOfType:(PropertyType)newPropertyType
rentingFor:(float)newRentalPrice
atAddress:(NSString *)newAddress;
Being a class method,rentalPropertyOfType:rentingFor:atAddress: allows you to invoke the
method without first creating an object.下面是此方法的实现:
+ (id)rentalPropertyOfType:(PropertyType)newPropertyType
rentingFor:(float)newRentalPrice
atAddress:(NSString *)newAddress
{
id newObject = [[CTRentalProperty alloc]
initWithAddress:newAddress
rentalPrice:newRentalPrice
andType:newPropertyType];
return [newObject autorelease];
}
注意,上面的代码用了本来就有的alloc和前面早就有的initWithAddress:rentingFor:andType: 方法。
还有就是还发送了一个autorelase消息,这和内存有关。
接下来就是谈谈如何销毁对象。If you don’t destroy these objects, they’ll eventually consume enough memory that the iPhone will think your application is the next Chernobyl and shut it
down to avoid impacting other phone functionality!
If you forget this step, the memory will forever hold your object even if you never use it again. In Objective-C (at least when targeting the iPhone), it’s your responsibility to manage memory usage explicitly.
Unlike languages such as C# and Java, Objective-C has no automated detection and reclaiming of unwanted objects, a feature commonly known as garbage collection.
CTRentalProperty *newRental = [[CTRentalProperty alloc]
initWithAddress:@"13 Adamson Crescent"
rentingFor:275.0f
andType:TownHouse];
... make use of the object ...
[newRental release];
newRental = nil;
尽管你应当调用release来指明你对此对象已经不感兴趣了,但这并不会确保立刻就把此对象销毁掉。
你的应用的其他部分可能还想此对象存活,只有当最后的一个引用被释放后,该对象才会被释放。
当release最后判断出没人还要此对象活着时,它就会自动调用另一个方法,叫dealloc,来清理掉
此对象。
如何实现CTRentalProperty的dealloc方法:
- (void)dealloc {
[address release];
[super dealloc];
}
在dealloc中也适合清理掉任何系统资源(如文件、网络sockets,或数据库handles)。
还有要注意,尽管declared properties可以自动提供getter和setter实现,但它们并没有在dealloc中
生成代码来释放它们关联的内存。如果你的类里有一些属性使用了retain或copy语义,你必须手动
在dealloc中编写清除它们所使用的内存的代码。上面代码中[address release]就是此用法。
Finally,most dealloc method implementations end with a call to [super dealloc].This gives
the superclass a chance to free any resources it has allocated.Notice that the order here
is important.
- 浏览: 145082 次
- 性别:
- 来自: 安徽
文章分类
- 全部博客 (185)
- Mule (2)
- linux (9)
- JavaScript相关总结 (2)
- 标准C++ (2)
- 数据库 (3)
- 数据结构 (2)
- Java (9)
- Oracle (8)
- 设计模式 (6)
- struts (1)
- Spring (2)
- Spring Security (1)
- Axis2 web service (3)
- IBM WebSphere应用服务器 (0)
- webservice (10)
- CXF (6)
- Ant (2)
- WebLogic Server (2)
- play (3)
- tomcat (5)
- Jsp (0)
- memcached (4)
- android (9)
- mongodb (0)
- jongo (0)
- scala (1)
- 软件安装 (1)
- flex (The View Layer) (0)
- mysql (1)
- ios (11)
- PhoneGap/Cordova (1)
- 线程 (1)
- ivy (1)
- xml (1)
- hadoop 0.20 (1)
- Hibernate (0)
- maven (0)
- Ajax (0)
- swift (0)
- objective-c开发ios (0)
- objective-c (11)
- nio (0)
- io (1)
- 操作系统 (1)
- ActiveMQ (0)
- apache (1)
- HBase (0)
- redis (1)
- python (6)
- SOA (0)
- nginx (3)
- angularJS (3)
- Node.js (5)
- JavaScript (3)
- PHP (5)
- 网络 (1)
- servlet jsp (1)
- jQuery (1)
- shell (4)
- CSS (0)
- spark (0)
- dwr (7)
- Couchbase (2)
- Sencha Architect (0)
- jQuery Mobile (0)
- jUnit (0)
- jetty (0)
- activiti (1)
- Git (1)
- Groovy (1)
- Gradle (4)
- MyBatis (0)
- Spring微服务 (1)
- Cocoa (0)
- Ext JS 4 (1)
- Varnish Cache (0)
- Django (1)
- Spring Boot (2)
- WordPress (0)
- ruby (0)
- react native (1)
- SpringBoot (1)
- eclipse (1)
- extjs 5 (1)
- 云计算 (0)
- kafka (0)
- GitHub (1)
- zookeeper (0)
- storm (0)
- Docker (0)
- Spring Cloud (2)
- 谷歌地图API (0)
- Jetty 9 (0)
- Spring 5响应式编程 (0)
- 字符集和校对规则 (0)
最新评论
-
小小西芹菜:
前段时间研究了一下goeasy,java后台推送只需要两行代码 ...
Reverse AJAX -
spp_1987:
现在服务都能启动, 就是怎么用java生成wsdl 不成。。。 ...
Apache Axis2 安装指南 -
spp_1987:
ai...
Apache Axis2 安装指南 -
zsjg13:
不好意思,我看了下我上面的描述,我发现我把insert语句中的 ...
ORA-02287: sequence number not allowed here问题的解决 -
StartNowFly:
没解决,还是报一样的错
ORA-02287: sequence number not allowed here问题的解决
发表评论
-
Message Forwarding
2015-11-29 02:02 457The object type can either be ... -
Message Dispatch
2015-11-29 01:30 525The receiving object (i.e., re ... -
Filling in the gaps—floating-point numbers
2015-11-28 23:05 486浮点常量也可以表示成科学或指数计数法。例如,下面的2句变量声 ... -
Counting on your fingers—integral numbers
2015-11-28 22:28 318An integer is a whole number t ... -
Declared properties
2015-11-28 00:38 0A property allows you to descr ... -
用Category来扩展一个类
2015-11-24 23:39 486想要给一个类添加方法和行为,但不想创建一个全新的子类。 ... -
给自定义类加类方法
2015-11-24 22:52 737在Objective-C中,你可以向类或对象发送消息来完成某 ... -
用Objective-C编写一个终端应用
2015-11-24 20:38 560在main函数中,必须建立一个autorelease poo ... -
Category
2015-07-10 22:39 0Category:无需子类化, ... -
Objective-C介绍
2015-07-10 20:34 654Objective-C是一门用于在Apple的OS X以及i ... -
Objective-C Protocol
2015-07-10 15:19 479已经学习了Objective-C类的基本元素和结构,但是该 ... -
objective-c方法
2015-07-10 15:10 410方法定义了类和类实例在运行时所表现出的行为。分2种:clas ...
相关推荐
在IT领域,尤其是在编程语言的学习与应用中,C#(C Sharp)作为一款由微软开发的面向对象的、类型安全的、垃圾回收的程序设计语言,其在创建和销毁对象方面的处理方式是开发者必须掌握的核心技能之一。...
7. **创建与销毁对象(Creating and Destroying Objects)**:"CSharp_Module 9_Creating and Destroying Objects.pdf"将涵盖对象的生命周期,包括构造函数、析构函数和垃圾回收机制,以及何时和如何适当地分配和释放...
2 Creating and Destroying Objects Item 1: Consider static factory methods instead of constructors Item 2: Consider a builder when faced with many constructor parameters Item 3: Enforce the singleton ...
7. **Creating and Destroying Objects**:学习如何创建和销毁对象,理解对象生命周期和垃圾回收机制。 8. **Inheritance in C#**:子类继承父类的属性和方法,实现代码重用和扩展。 9. **Aggregation, Namespaces...
模块9:《C# - Module 9_Creating and Destroying Objects.pdf》 本模块讲解了对象的生命周期,包括构造函数和析构函数的使用,以及垃圾回收机制。学习者将了解如何在适当的时间创建和释放对象,以优化内存管理。 ...
Contents Introduction Course Materials..................Creating and Destroying Objects...........................................................................16 Demonstration: Creating Classes.....
Creating and Destroying Objects.......................................................................16 Demonstration: Creating Classes..................................................................
Creating and Destroying Objects.................................................................16 Demonstration: Creating Classes.................................................................23 ...
Creating and Destroying Objects.................................................................16 Demonstration: Creating Classes.................................................................23 ...
- **Trigger Volumes and Destroying Actors**: Detecting when actors should be removed. - **Debugging Our Blueprints**: Identifying and fixing issues. - **Masking Our Destruction with Particles**: ...
接着,3.4节“Creating and Destroying Tcl Objects”介绍了如何创建和销毁Tcl对象,3.4.2节“Variable Bindings”讲解了变量绑定,3.4.3节“Variable Tracing”讲述了变量追踪,3.4.4节“command Methods: ...