Objective C,NSMutableDictionary 引用计数
NSMutableDictionary *attrs = [nodeAttributes objectForKey:UUID];//nodeAttributes is NSMutalbleDictionary
if (attrs == nil) {
attrs = [[NSMutableDictionary alloc] init];
[nodeAttributes setObject:attrs forKey:UUID];
[attrs release];
}
我不确定这段代码是否有效...我应该有这样的东西而不是这个
NSMutableDictionary *attrs = [nodeAttributes objectForKey:UUID];//nodeAttributes is NSMutalbleDictionary
if (attrs == nil) {
attrs = [[NSMutableDictionary alloc] init];
[nodeAttributes setObject:[attrs retain] forKey:UUID];
[attrs release];
}
我不确定 setObject 方法是否会增加引用计数...
NSMutableDictionary *attrs = [nodeAttributes objectForKey:UUID];//nodeAttributes is NSMutalbleDictionary
if (attrs == nil) {
attrs = [[NSMutableDictionary alloc] init];
[nodeAttributes setObject:attrs forKey:UUID];
[attrs release];
}
I am not sure this code will works...Should I have something like this instead of this
NSMutableDictionary *attrs = [nodeAttributes objectForKey:UUID];//nodeAttributes is NSMutalbleDictionary
if (attrs == nil) {
attrs = [[NSMutableDictionary alloc] init];
[nodeAttributes setObject:[attrs retain] forKey:UUID];
[attrs release];
}
I am not sure if setObject method will increase the reference count...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
NSMutableDictionary 的
setObject
将保留该对象(这是 记录),因此代码的第一位是正确的,而第二位则泄漏。从风格角度来看,读者执行以下操作可能会更清楚:虽然从内存管理角度来看,您的方法可能更好,因为它避免(隐式)使用自动释放。
NSMutableDictionary's
setObject
will retain the object (this is documented), so the first bit of code is correct and the second leaks. Style-wise, it may be more clear to a reader to do the following:Although memory-management-wise, your approach is probably better in that it avoids (implicitly) using autorelease.
在第一种情况下,保留计数将增加。这才是正确的做法。
The retain count will be incremented in the first case. That's the correct approach.
对象负责声明其拥有的事物的所有权。所以是的,
setObject:forKey:
将保留。 Apple 的 内存管理指南。Objects are responsible for claiming ownership of the things they own. So yes,
setObject:forKey:
will retain. This is explained in detail (but still very briefly) in Apple's memory management guide.setObject 将发送一条保留消息,因此您不需要这样做。
setObject will send a retain message so you don't need to do that.