在NSCoding Protocol方法的实现中释放时崩溃

时间:2012-10-25 13:45:13

标签: objective-c nscoding

以下是我用于取消归档数据的代码:

- (id)initWithCoder:(NSCoder *)decoder
{
    if((self = [super init]))
    {
        NSString *resoureItemClassName = NSStringFromClass([ResourceItem class]);
        self.selectedItemClassName=[decoder decodeObjectForKey:@"selectedItemClassName"];
        Class class = NSClassFromString(selectedItemClassName);
        id temp = nil;

        if(class)
        {      
            temp = [[class alloc] init];
        }

        if(temp)
        {
            if([temp isKindOfClass:[NSString class]])
            {
                self.selectedString = [decoder decodeObjectForKey:@"selectedString"];;
                self.ID = selectedString;
            }
            else if([selectedItemClassName isEqualToString:resoureItemClassName])
            {  
                DLog(@"Resource item")
            }

            [temp release];                         
        }
        else
        {    
            self.ID = nil;
        }
    }

    return self;
}

当我发布tempObject时,应用程序崩溃了。如果我不这样做,那就是泄漏。我尝试使用自动释放方法。它还在崩溃吗?解决办法是什么?

更新

selectedItemClassName中的编码数据是__NSCFConstantString或__NSCFString。崩溃只发生在__NSCFString而不是__NSCFConstantString作为类名,

可能是什么原因?

1 个答案:

答案 0 :(得分:0)

怎么样:

- (id)initWithCoder:(NSCoder *)decoder
{
    if((self = [super init]))
    {
        NSString *resourceItemClassName = NSStringFromClass([ResourceItem class]);
        self.selectedItemClassName=[decoder decodeObjectForKey:@"selectedItemClassName"];
        Class class = NSClassFromString(selectedItemClassName);

        if(class)
        {      
            NSString *stringClassName = NSStringFromClass([NSString class]);
            if([stringClassName isEqualToString:self.selectedItemClassName])
            {
                self.selectedString = [decoder decodeObjectForKey:@"selectedString"];;
                self.ID = selectedString;
            }
            else if([self.selectedItemClassName isEqualToString:resourceItemClassName])
            {  
                DLog(@"Resource item")
            }
        }
        else
        {    
            self.ID = nil;
        }
    }

    return self;
}