目标C:关于分配,保留和释放的新手问题 [英] Objective C: Newbie question about allocation, retain and release
问题描述
对于OC来说是新手,多年使用C,C ++,C#,现在头脑有点呆滞.
New to OC, many years of C, C++, C#, mind is kind of boggled now.
给出:
// AnInterface.h
@interface AnInterface : NSObject
{
}
@property (retain) SomeObject* m_Object;
// AnInterface.m
#import "AnInterface.h"
@synthesize m_Object;
-init
{
self= [super init];
if(!self)
return (nil);
SomeObject* pObject= [[SomeObject alloc] init];
self.m_Object= pObject;
[pObject release];
}
我很确定上面的说法是正确的.然而, 为什么不这样做:
I am pretty sure the above is correct. However, why not just do:
self.m_Object= [[SomeObject alloc] init];
这还行吗?是否违反某些内存管理原则?似乎应该起作用,一行而不是三行,但是我敢肯定我一定会遗漏一些东西....
Does that work as well? Is it in violation of some memory management tenet? It seems like it should work, one line rather than three, but I am certain I must be missing something....
任何见识都会受到赞赏.
Any insight would be appreciated.
推荐答案
原因是因为您将属性m_Object定义为保留,所以它会导致内存泄漏,因为alloc/init调用会导致保留+1,然后保留属性会保留至少给+2的保留数.如果您愿意,请随意使用自动发布池.
The reason is because you defined the property m_Object to retain so it would result in a memory leak because alloc/init call results in a retain of +1 then property will retain giving it at least a retain count of +2. If you would like to make it one line feel free to abuse the auto release pool.
self.m_Object= [[[SomeObject alloc] init] autorelease];
这篇关于目标C:关于分配,保留和释放的新手问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!