本文介绍了是否释放Objective-c 2.0属性的内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在想知道一段时间的属性。当您使用属性时,是否需要覆盖发布消息以确保属性已释放属性?

Something I have been wondering about properties for a while. When you are using properties, do you need to override the release message to ensure the properties are released properties?

ie )示例是否足够?

@interface MyList : NSObject {
NSString* operation;
NSString* link;
}
@property (retain) NSString* operation;
@property (retain) NSString* link;
@end

@implementation MyList
@synthesize operation,link;
@end


推荐答案

在dealloc中支持变量:

You should always release the backing variables in dealloc:

- (void) dealloc {
   [operation release];
   [link release];

   [super dealloc];
}

另一种方式:

- (void) dealloc {
   self.operation = nil;
   self.link = nil;

   [super dealloc];
}

这不是发布对象的首选方式,

That's not the preferred way of releasing the objects, but in case you're using synthesized backing variables, it's the only way to do it.

注意:为了清楚说明为什么会这样做,让我们来看看合成的背景变量

NOTE: to make it clear why this works, let's look at the synthesized implementation of the setter for link property, and what happens when it is set to nil:

- (void) setLink:(MyClass *) value {
   [value retain]; // calls [nil retain], which does nothing
   [link release]; // releases the backing variable (ivar)
   link = value;   // sets the backing variable (ivar) to nil
}

它会释放ivar。

这篇关于是否释放Objective-c 2.0属性的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 17:02