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.
- 浏览: 137963 次
- 性别:
- 来自: 安徽
文章分类
- 全部博客 (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 421The object type can either be ... -
Message Dispatch
2015-11-29 01:30 493The receiving object (i.e., re ... -
Filling in the gaps—floating-point numbers
2015-11-28 23:05 442浮点常量也可以表示成科学或指数计数法。例如,下面的2句变量声 ... -
Counting on your fingers—integral numbers
2015-11-28 22:28 281An 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 453想要给一个类添加方法和行为,但不想创建一个全新的子类。 ... -
给自定义类加类方法
2015-11-24 22:52 703在Objective-C中,你可以向类或对象发送消息来完成某 ... -
用Objective-C编写一个终端应用
2015-11-24 20:38 525在main函数中,必须建立一个autorelease poo ... -
Category
2015-07-10 22:39 0Category:无需子类化, ... -
Objective-C介绍
2015-07-10 20:34 626Objective-C是一门用于在Apple的OS X以及i ... -
Objective-C Protocol
2015-07-10 15:19 445已经学习了Objective-C类的基本元素和结构,但是该 ... -
objective-c方法
2015-07-10 15:10 378方法定义了类和类实例在运行时所表现出的行为。分2种:clas ...
相关推荐
CSharp - Module 9_Creating and Destroying Objects
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 ...
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 ...
Contents Introduction Course Materials..................Creating and Destroying Objects...........................................................................16 Demonstration: Creating Classes.....
Instead, closing and destroying the client and re-creating it. Sleeping on error before re-creating client and continuing to process Deal with thread-safety issues on shared memory between threads ...
floppy disks and other media, (c) considerations for handling CD and DVD evidence to both recover the maximum amount of information present on a disc and to do so without destroying or altering the ...
Destroying Objects 79 Passing Parameters 83 iv | Table of Contents Overloading Methods and Constructors 89 Encapsulating Data with Properties 92 readonly Fields 96 5. Inheritance and Polymorphism . . ...
Chapter 12: Creating and Managing Menus 169 Introduction 169 Creating a menu 170 Adding menu buttons 175 Displaying a pop-up menu 178 Data entry application 180 Chapter 13: Creating the Address Book ...
PythonForDelphi 修改 最后修改日期2019-2-1这一版,需要注意的是python 3.7 要安装32位版 需要在Delphi中先安装上Python...Demo34 Dynamically creating, destroying and recreating PythonEngine. Uses PytonVersions
Raiden consists of eight vertical scrolling missions where the player pilots the "Raiden Supersonic Attack Fighter" through waves of enemies, dodging and destroying enemy buildings, ground targets, ...
Creating and Deleting a Process Address Space Section 9.6. Managing the Heap Chapter 10. System Calls Section 10.1. POSIX APIs and System Calls Section 10.2. System Call Handler and Service Routines ...
Pro PHP Security guides developers through many of the defensive and proactive security measures that can be taken to help prevent attackers from potentially disrupting site operation or destroying ...
Improved : block refreshing columns when destroying the component in TTMSFMXSpinner Fixed : Small issue in HTML Rendering engine for anchor rendering in TTMSFMXHTMLEngine Fixed : Issue with ...
Likewise, his namesake, Timothy “Thor” Mullen, has spent his entire adult life both destroying and restoring Microsoft-based security systems. Thor’s Microsoft Security Bible conveys the wisdom ...
Q520547 - TcxVirtualVerticalGrid - Possible exception in the TcxvgPainter.DrawRow method when destroying and recreating rows within the BeginUpdate/EndUpdate block Q525420 - The Styles....
Q520547 - TcxVirtualVerticalGrid - Possible exception in the TcxvgPainter.DrawRow method when destroying and recreating rows within the BeginUpdate/EndUpdate block Q525420 - The Styles....
Subject to the terms of this Laboratory and Developer License, POLYCOM grants you a limited, non-exclusive, non-transferable license to install and use, on a DEVICE, the number and type of SOFTWARE ...
theoretical side of his profession, which is especially reassuring considering his constant fear of accidentally destroying the universe. Outside his research work, he is fascinated by operating ...