分析器标记了该结构的潜在泄漏

发布于 2024-08-24 01:36:25 字数 624 浏览 5 评论 0原文

使用以下代码,分析器将 setMyDict 选择器调用标记为潜在泄漏,并在 dealloc 中指出“调用者此时不拥有引用计数的错误递减”

- (id)init {
  if (self = [super init]) {
      [self setMyDict:[[NSMutableDictionary alloc] init]];
  }
  return self;
}

- (void)dealloc {
  [[self myDict] release];
  [super dealloc];
}

@synthesize myDict = _myDict;

我不明白这一点。我认为,通过 alloc init ,对象将保留计数增加一,并且指针通过合成属性存储在 _myDict 中。如果我使用此代码,

- (id)init {
  if (self = [super init]) {
    _myDict = [[NSMutableDictionary alloc] init];
  }
  return self;
}

- (void)dealloc {
  [_myDict release];
  [super dealloc];
}

分析器不会抱怨。我缺少什么?

With the following code the analyzer marks the setMyDict selector call as a potential leak and in dealloc it states "Incorrect decrement of the reference count is not owned at this point by the caller"

- (id)init {
  if (self = [super init]) {
      [self setMyDict:[[NSMutableDictionary alloc] init]];
  }
  return self;
}

- (void)dealloc {
  [[self myDict] release];
  [super dealloc];
}

@synthesize myDict = _myDict;

I do not understand this. I thought, that with the alloc init the object increases the retain count by one and the pointer is stored in _myDict through the synthesized property. If I use this code instead

- (id)init {
  if (self = [super init]) {
    _myDict = [[NSMutableDictionary alloc] init];
  }
  return self;
}

- (void)dealloc {
  [_myDict release];
  [super dealloc];
}

Analyzer does not complain. What am I missing?

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

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

发布评论

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

评论(1

泪之魂 2024-08-31 01:36:25

@synthesize 为您正在合成的对象提供了 setter 和 getter。

setter 方法看起来像这样(摘自 Apple 文档):

-(void)setMyDict:(NSMutableDictionary *)newDict {
    if (myDict != newDict) {
       [myDict release];
       myDict = [newDict retain];
    }
}

当您这样做时,您正在创建泄漏:

[self setMyDict:[[NSMutableDictionary alloc] init]];

因为您从未释放新分配的字典。

解决这个问题的一种方法是:

NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
[self setMyDict:dict];
[dict release];

这可以解决泄漏问题。

在 dealloc 方法中,您应该使用:

[myDict release]; // Or whatever your property is called.

The @synthesize provides you with a setter and getter for the object you're synthesizing.

A setter method looks something like this (taken from the Apple docs)

-(void)setMyDict:(NSMutableDictionary *)newDict {
    if (myDict != newDict) {
       [myDict release];
       myDict = [newDict retain];
    }
}

You're creating a leak when you do:

[self setMyDict:[[NSMutableDictionary alloc] init]];

Because you never release the newly alloc'd dictionary.

A way to work around this is:

NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
[self setMyDict:dict];
[dict release];

This takes care of the leak.

In the dealloc method, you should use:

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