我有这个代码:
Entry.h
#import@interface Entry : NSObject { id object; SEL function; } @property (retain) id object; @property (assign) SEL function; -(Entry*) initWithObject:(id)object selector:(SEL)function; @end
Entry.m
#import "Entry.h" @implementation Entry @synthesize object; @synthesize function; -(Entry*) initWithObject:(id)obj selector:(SEL)sel { self = [super init]; [self setObject:obj]; [self setFunction:sel]; return self; } -(void) dealloc { [super dealloc]; if ([self object] != nil) [[self object] release]; } @end
当我这样做时:
Entry *hej = [Entry alloc]; [hej release];
我明白了:
objc[2504]: FREED(id): message object sent to freed object=0xf5ecd0 Program received signal: “EXC_BAD_INSTRUCTION”.
我究竟做错了什么?
(并且这个插入代码在堆栈溢出的东西不起作用,除非我做错了,你不应该点击"代码示例"然后粘贴.)
+alloc
只分配内存.您需要-init
在该内存空间中实际创建对象.由于您只是分配内存而不是在那里创建对象,因此调用-release
一块内存会给您一个错误.此外,您希望您的[super dealloc]
呼叫显示在-dealloc
方法的末尾.改变这两件事,以下内容应该有效:
Entry *hej = [[Entry alloc] init]; [hej release];