我真的很困惑这一点。我相信我正在以正确的方式管理内存,但执行代码表明我正在双重释放对象。这里是代码,然后我会解释发生了什么。双重发布时不应该发生
@protocol SomeDelegate <NSObject>
@required
- (id)initWithCols:(NSUInteger)Cols Rows:(NSUInteger)Rows;
@end
@interface SomeObject : NSObject <SomeDelegate> {
}
- (id)initWithCols:(NSUInteger)Cols Rows:(NSUInteger)Rows;
@end
@interface Layout : UIView {
id<SomeDelegate> someDelegate;
}
@property(retain) id<SomeDelegate> someDelegate;
- (id)initWithFrame:(CGRect)aRect Cols:(NSUInteger)Cols Rows:(NSUInteger)Rows;
@end
@implementation Layout
@synthesize someDelegate;
- (id)initWithFrame:(CGRect)aRect Cols:(NSUInteger)Cols Rows:(NSUInteger)Rows {
if(self = [super initWithFrame:aRect]) {
cols = Cols;
rows = Rows;
id<SomeDelegate> delegate = [[SomeObject alloc] initWithCols:cols Rows:rows];
[self setSomeDelegate:delegate];
//[delegate release];
}
return self;
}
-(void)dealloc {
[someDelegate release];
[super dealloc];
}
@end
现在,当我去掉了 “// [委托释放];”在Layout类的构造函数中,然后我得到一个“EXC_BAD_ACCESS”错误,当它尝试释放时,应用程序崩溃。我已经将崩溃追溯到Layout类的dealloc方法中释放someDelegate对象。如果我留下评论,那么应用程序工作正常。
有人能解释为什么会发生这种情况,因为它似乎违背了我在Objective-C中有关内存管理的所有内容。
只是说明该代码示例实际工作,但是我的代码不符合该示例。我的实际SomeObject中是否会引起autorelease?
在此先感谢。
出于好奇,如果将“委托”变量重命名为其他内容,会发生什么?我知道这应该不重要,但我记得按照同样的方法在cocoa-dev邮件列表中阅读了一些内容;奇怪的行为与某些变量名称。 UIView有它自己的委托,我想知道它是否与此有关。 – dreamlax 2009-06-29 22:48:44
好想法,但不幸的是我尝试将它重命名为委托,它仍然有释放问题。 – 2009-06-29 23:24:09