【发布时间】:2010-03-21 21:43:00
【问题描述】:
使用嵌套工厂方法处理内存管理的最佳方法是什么,如下例所示?
@interface MyClass : NSObject {
int _arg;
}
+ (MyClass *) SpecialCase1;
+ (MyClass *) SpecialCase2;
+ (MyClass *) myClassWithArg:(int)arg;
- (id) initWithArg:(int)arg;
@property (nonatomic, assign) int arg;
@end
@implementation MyClass
@synthesize arg = _arg;
+ (MyClass *) SpecialCase1
{
return [MyClass myClassWithArg:1];
}
+ (MyClass *) SpecialCase2
{
return [MyClass myClassWithArg:2];
}
+ (MyClass *) myClassWithArg:(int)arg
{
MyClass *instance = [[[MyClass alloc] initWithArg:arg] autorelease];
return instance;
}
- (id) initWithArg:(int)arg
{
self = [super init];
if (nil != self) {
self.arg = arg;
}
return self;
}
@end
这里的问题(我认为)是自动释放池在 SpecialCaseN 方法返回给它们的调用者之前被刷新[编辑:显然不是 - 见下面的 cmets]。因此,SpecialCaseN 的最终调用者不能依赖已保留的结果。 (在尝试将 [MyClass SpecialCase1] 的结果分配给另一个对象的属性时,我得到“[MyClass copyWithZone:]: unrecognized selector sent to instance 0x100110250”。)
需要 SpecialCaseN 工厂方法的原因是,在我的实际项目中,初始化实例需要多个参数,并且我有一个我希望能够创建的“模型”实例的预定义列表很容易。
我确信有比这更好的方法。
[编辑:根据请求添加@interface。]
【问题讨论】:
-
可以发一下MyClass的界面吗? (另外,我会为这个类写一个 dealloc 方法,如果只是为了完整性)
-
完成。 (这是一个简化的示例,改编自我正在爆炸的实际课程。)
标签: iphone objective-c xcode macos