在引用计数的环境下管理内存使用的基本模型是,通过在NSObject协议定义的方法和提供标准命名的方法。NSObject类也定义了一个方法“dealloc”,当一个对象被释放时此函数被调用。本文介绍了您需要知道的,如何正确的管理内存在一个Cocoa程序,并提供了一些正确的使用实例。
内存管理模型是基于对象所有权的。任何一个对象可能会有一个或者多个所有者。只要一个对象有至少一个所有者,那么它需要继续退出。当一个对象没有所有者时,系统会自动销毁它。
为了确保你是否清除一个对象,Cocoa提供以下策略:
为了说明该策略,考虑下面的代码片段:
{
Person *aPerson = [[Person alloc] init];
// ...
NSString *name = aPerson.fullName;
// ...
[aPerson release];
}
当需要放送一个延迟释放消息时,你可以使用autorelease。这通常是在返回一个对象方法时使用。下面举一个例子,你可以实现获取人的名字方法像这样:
- (NSString *)fullName {
NSString *string = [[[NSString alloc] initWithFormat:@"%@ %@",
self.firstName, self.lastName] autorelease];
return string;
}
也可以用下面的方式实现:
- (NSString *)fullName {
NSString *string = [NSString stringWithFormat:@"%@ %@",
self.firstName, self.lastName];
return string;
}
相比之下,下面的实现方式是错误的:
- (NSString *)fullName {
NSString *string = [[NSString alloc] initWithFormat:@"%@ %@",
self.firstName, self.lastName];
return string;
}在Cocoa框架中有一些特殊的方法,他们返回对象的引用(他们的参数类型可能是ClassName**或者id*)。比较常见的方法就是,当发生了一个错误,通过NSError保存出错信息。如下所示:
initWithContentsOfURL:options:error: (NSData) and initWithContentsOfFile:encoding:error: (NSString).
NSString *fileName = <#Get a file name#>;
NSError *error;
NSString *string = [[NSString alloc] initWithContentsOfFile:fileName
encoding:NSUTF8StringEncoding error:&error];
if (string == nil) {
// Deal with error...
}
// ...
[string release];
NSObject类定义了dealloc方法。当对象没有拥有者,或者内存被回收时,该方法自动调用。这个方法的作用是释放对象的内存,并处理它拥有的任何资源,包括任何对象实例变量的所有权。
下面这个例子描述怎么实现Person类的dealloc方法:
@interface Person : NSObject
@property (retain) NSString *firstName;
@property (retain) NSString *lastName;
@property (assign, readonly) NSString *fullName;
@end
@implementation Person
// ...
- (void)dealloc
[_firstName release];
[_lastName release];
[super dealloc];
}
@end在dealloc函数实现方法结束前,要调用父类的dealloc方法。
不应该把系统资源的管理放到对象生命周期中;不用用dealloc方法管理稀缺资源。
当应用程序中断时,对象不可能发送dealloc消息。因为进程的内存在退出时自动清除,所以更高效的操作系统来清除资源,而不是调用所有的内存管理方法。
有类似的管理规则给核心库对象。Cocoa和核心库的命名规则是不同的。特别是核心库的创建规则不适用于返回Objective-C对象的方法。
举一个例子,在下面的代码段中,你不负责释放myInstance实例所有权的。
MyClass *myInstance = [MyClass createInstance];
原文地址:http://blog.csdn.net/th_gsb/article/details/47087325