Objective C,NSMutableDictionary 引用计数

发布于 2024-10-21 11:49:27 字数 681 浏览 3 评论 0原文

    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 技术交流群。

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

发布评论

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

评论(4

小糖芽 2024-10-28 11:49:27

NSMutableDictionary 的 setObject 将保留该对象(这是 记录),因此代码的第一位是正确的,而第二位则泄漏。从风格角度来看,读者执行以下操作可能会更清楚:

if (attrs == nil) {
     attrs = [NSMutableDictionary dictionary];
     [nodeAttributes setObject:attrs forKey:UUID];
}

虽然从内存管理角度来看,您的方法可能更好,因为它避免(隐式)使用自动释放。

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:

if (attrs == nil) {
     attrs = [NSMutableDictionary dictionary];
     [nodeAttributes setObject:attrs forKey:UUID];
}

Although memory-management-wise, your approach is probably better in that it avoids (implicitly) using autorelease.

抚你发端 2024-10-28 11:49:27

在第一种情况下,保留计数将增加。这才是正确的做法。

The retain count will be incremented in the first case. That's the correct approach.

沧笙踏歌 2024-10-28 11:49:27

对象负责声明其拥有的事物的所有权。所以是的,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.

绿萝 2024-10-28 11:49:27

setObject 将发送一条保留消息,因此您不需要这样做。

setObject will send a retain message so you don't need to do that.

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