Objective C - init 是实现工厂的坏地方吗? [英] Objective C - is init a bad place to implement a factory?
问题描述
我实现了旧的 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.
所以看起来:
- 释放
self
并从init
返回一个新对象,严格来说是违反规则的. - 互联网上的许多地方都在推广这种技术,而且由于 alloc/init 的串联性质,这确实有效.
- 分析器有时会抱怨这一点,有时不会.
- Releasing
self
and returning a new object frominit
is, strictly speaking, against the rules. - Many places on the internet promote this technique, and because of the tandem nature of alloc/init this does work.
- 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
实现为工厂方法.例如NSArray
、NSDictionary
、NSString
and it if very often to implement init
as a factory method. e.g. NSArray
, NSDictionary
, NSString
这篇关于Objective C - init 是实现工厂的坏地方吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!