为什么我不应该释放这个字符串?
看下面的方法:
-(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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不应该释放它,因为您没有
+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.更好的问题是:为什么应该发布它?您做了什么来声明该对象的所有权?在这种情况下,答案是“什么也没有”。由于您不拥有它,因此您无法很好地释放它。
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.