为什么我不应该释放这个字符串?

发布于 2024-08-21 19:52:25 字数 782 浏览 5 评论 0原文

看下面的方法:

-(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。
有人可以向我解释为什么释放这些对象是错误的吗?

Look at the following method:

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

I have commented out two lines, which gives me EXC_BAD_ACCESS if not.
Can someone explain to me why it's wrong to release these objects?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一生独一 2024-08-28 19:52:25

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

You shouldn't release it because you didn't +alloc, -retain, or -copy it. Convenience constructors like +objectWith… return autoreleased objects.

南街九尾狐 2024-08-28 19:52:25

更好的问题是:为什么应该发布它?您做了什么来声明该对象的所有权?在这种情况下,答案是“什么也没有”。由于您不拥有它,因此您无法很好地释放它。

The better question to ask is: Why should you release it? What have you done to claim ownership over the object? The answer in this case is "nothing." Since you don't own it, you can't very well release it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文