Objective C - init 是实现工厂的坏地方吗? [英] Objective C - is init a bad place to implement a factory?

查看:52
本文介绍了Objective C - init 是实现工厂的坏地方吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实现了旧的 init-as-a-factory 模式,但在一种特殊情况下(但不是其他情况!),我从分析器收到关于内存泄漏的警告.事实上,查看 Cocoa 内存管理政策规则,是alloc,不是init,可以返回+1-retain-count个对象.

I implemented the old init-as-a-factory pattern, but in one particular case (but not others!) I get a warning from the analyser regarding memory leaks. And indeed, looking at the Cocoa Memory Management Policy rules, it is alloc, not init, which can return +1-retain-count objects.

所以看起来:

  1. 释放 self 并从 init 返回一个新对象,严格来说是违反规则的.
  2. 互联网上的许多地方都在推广这种技术,而且由于 alloc/init 的串联性质,这确实有效.
  3. 分析器有时会抱怨这一点,有时不会.
  1. Releasing self and returning a new object from init is, strictly speaking, against the rules.
  2. Many places on the internet promote this technique, and because of the tandem nature of alloc/init this does work.
  3. The analyser sometimes complains about this, and sometimes doesn't.

那么……我们一直都做错了吗?

So... have we been doing this wrong all along?

推荐答案

你可以像这样实现 init ,它应该释放 self 以平衡 alloc 调用.

you can implemented init like this, which should release self to balance the retain count from alloc call.

- (id)initWithSomething:(id)something
{
    [self release]; // don't need this line for ARC
    self = nil;
    return [[PrivateSubClass alloc] initWithSomething:something];
}

并且经常将 init 实现为工厂方法.例如NSArrayNSDictionaryNSString

and it if very often to implement init as a factory method. e.g. NSArray, NSDictionary, NSString

这篇关于Objective C - init 是实现工厂的坏地方吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆