Elton's Blog

Tag: nil

如何正确释放Properties变量

by on 十二.14, 2009, under Mac

今天在看iPhone Development Cookbook 2nd Edition的时候,学习到如何正确释放Properties变量。
例如你有一个Properties变量:

1
2
@property (retain) NSArray *colors;
self.colors = [NSArray arrayWithObjects:@"Gray", @"Silver", @"Black"];

如何正确释放呢? 正确的方式是

1
self.colors = nil;

这样Objective-c先release原先的colors变量,然后再将nil赋值给colors。

可能你觉得这样也可以

1
[self.colors release];

但是这样可能会导致一个错误出现,因为你现在release了这个变量,减少了它的retain计数,比如从1减为0,当下次再为这个变量进行复制的时候,因为objective-c会先release这个变量,所以就导致两次release,会导致系统崩溃。

4 Comments :, , more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit my friends!

A few highly recommended friends...