为什么我不应该发布这个字符串?

Veg*_*gar 2 release exc-bad-access objective-c

请看以下方法:

-(void)updateProfile:(Profile *)profile WithJSON:(NSString *)JSON;
{
    SBJSON *parser = [[SBJSON alloc] init];
    NSDictionary *object = [parser objectWithString:JSON error:nil];

    NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
    [nf setPositiveFormat:@"#,##0"];

    profile.displayName = [object valueForKey:@"displayName"];
    profile.profileURL = [object valueForKey:@"profileURL"];

    NSString *rep = [object valueForKey:@"reputation"];
    profile.reputation = [[nf numberFromString:rep] intValue];
    //[rep release];   <-Why not release?

    [nf release];        
    //[object release];  <-Why not release?
    [parser release];
}
Run Code Online (Sandbox Code Playgroud)

我已经注释掉了两行,如果没有,它会给我EXC_BAD_ACCESS.
有人可以向我解释为什么发布这些对象是错误的吗?

NSR*_*der 14

因为你没有你不应该释放它+alloc,-retain或者-copy它.方便构造函数,如+objectWith…返回自动释放的对象.


Chu*_*uck 5

更好的问题是:你为什么释放它?你有什么办法要求拥有对象的所有权?在这种情况下,答案是"什么都没有".既然你没有它,你就不能很好地发布它.