【问题标题】:why shouldn't I release this string?为什么我不应该释放这个字符串?
【发布时间】:2011-01-17 03:32:00
【问题描述】:

看下面的方法:

-(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];
}

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

【问题讨论】:

    标签: objective-c release exc-bad-access


    【解决方案1】:

    更好的问题是:为什么应该发布它?你做了什么来声明对该对象的所有权?在这种情况下,答案是“没有”。既然你不拥有它,你就不能很好地释放它。

    【讨论】:

    • 猜猜我必须停止破坏其他人的财产......谢谢。
    【解决方案2】:

    你不应该发布它,因为你没有 +alloc-retain-copy 它。像+objectWith… 这样的便利构造函数返回自动释放的对象。

    【讨论】:

    • 谢谢!哇。这很明显......它也解决了我认为来自 RegexKitLite 框架的一些问题。总有一天,我会得到这个。我希望...
    猜你喜欢
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    • 1970-01-01
    • 2011-12-18
    • 2010-12-03
    • 2012-12-18
    相关资源
    最近更新 更多