菜鸟教程小白 发表于 2022-12-11 22:09:20

objective-c - 从 NSMutableDictionary 派生时,FastEnumeration 中的明显内存泄漏


                                            <p><p>我有一个类作为 NSMutableDictionary 的子类(主要是通过委托(delegate)),因为我们有一些自定义接口(interface)包裹在字典周围。运行 ios 泄漏工具时,它会将我的 keyEnumerator 方法识别为 NSFastEnumerationEnumerator 对象的泄漏源。</p>

<p>这是我作为封装的 NSMutableDictionary 的委托(delegate)的 keyEnumeration 方法。</p>

<pre><code>- (NSEnumerator*) keyEnumerator {
    return ;
}
</code></pre>

<p>泄漏的回溯总是显示一个枚举器作为源:</p>

<pre><code>- (void) someMethod {
    for (NSString *key in myWrappedDictionary) { ... }
}
</code></pre>

<p>这是一个典型的回溯:</p>

<pre><code>calloc
class_createInstance
__CFAllocateObject2
-
-
-[NSDictionary countByEnumerating...
-
</code></pre>

<p>我正在寻找我的一行代码中的解决方法或缺陷。我正在使用 ARC。</p>

<p>一个示例类如下所示。调用 将创建 9 个泄漏。</p>

<pre><code>@interface WrappedDictionary : NSMutableDictionary {
    NSMutableDictionary *dictionary;
}
- (id) init;
- (NSUInteger) count;
- (NSEnumerator*) keyEnumerator;
- (void)setObject:(id)anObject forKey:(id)key;
@end
@implementation WrappedDictionary
- (id) init{
    dictionary = ;
    return self;
}
- (NSUInteger) count { return ; }
- (NSEnumerator*) keyEnumerator {
    return ;
}
- (void)setObject: anObject forKey:key {
    ;
}
+ (void) createLeaks {
    for (int i=0; i &lt; 10; i++) {
      WrappedDictionary *dict = ;
      ;
      ;
      ;
      for (NSString *key in dict) {
            NSLog(@&#34;key=%@&#34;,key);
      }
    }
}
@end
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>请记住,泄漏工具只是显示泄漏的内存块<em>分配</em>的位置。这并不意味着分配点是泄漏的来源。更可能的泄漏源在 <code>someMethod</code> 中,或者在 <code>someMethod</code> 的调用者中,特别是如果您将其放入 ivar 然后对整个对象进行保留循环.</p></p>
                                   
                                                <p style="font-size: 20px;">关于objective-c - 从 NSMutableDictionary 派生时,FastEnumeration 中的明显内存泄漏,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/9795683/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/9795683/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: objective-c - 从 NSMutableDictionary 派生时,FastEnumeration 中的明显内存泄漏