释放对象的问题

qua*_*ano 1 cocoa cocoa-touch objective-c

我有这个代码:

Entry.h

#import <Foundation/Foundation.h>

@interface Entry : NSObject {
    id object;
    SEL function;
}

@property (retain) id object;
@property (assign) SEL function;

-(Entry*) initWithObject:(id)object selector:(SEL)function;

@end
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

当我这样做时:

Entry *hej = [Entry alloc];
[hej release];
Run Code Online (Sandbox Code Playgroud)

我明白了:

objc[2504]: FREED(id): message object sent to freed object=0xf5ecd0
Program received signal:  “EXC_BAD_INSTRUCTION”.
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

(并且这个插入代码在堆栈溢出的东西不起作用,除非我做错了,你不应该点击"代码示例"然后粘贴.)

Mar*_*don 7

+alloc只分配内存.您需要-init在该内存空间中实际创建对象.由于您只是分配内存而不是在那里创建对象,因此调用-release一块内存会给您一个错误.此外,您希望您的[super dealloc]呼叫显示在-dealloc方法的末尾.改变这两件事,以下内容应该有效:

Entry *hej = [[Entry alloc] init];
[hej release];
Run Code Online (Sandbox Code Playgroud)