【发布时间】:2013-08-24 19:34:08
【问题描述】:
我从 Appledoc 中读到了关于著名(或臭名昭著?)init 方法的这篇文章
在某些情况下,init 方法可能会返回一个替代对象。因此,在后续代码中,您必须始终使用 init 返回的对象,而不是 alloc 或 allocWithZone: 返回的对象。
所以说我有这两个类
@interface A : NSObject
@end
@interface B : A
@property (nonatomic, strong) NSArray *usefulArray;
@end
使用以下实现
@implementation A
+(NSMutableArray *)wonderfulCache {
static NSMutableArray *array = nil;
if (!array)
array = [NSMutableArray array];
return array;
}
-(id)init {
if (self=[super init]) {
// substituting self with another object
// A has thought of an intelligent way of recycling
// its own objects
if ([self.class wonderfulCache].count) {
self = [self.class wonderfulCache].lastObject;
[[self.class wonderfulCache] removeLastObject];
} else {
// go through some initiating process
// ....
if (self.canBeReused)
[[self.class wonderfulCache] addObject:self];
}
}
return self;
}
-(BOOL) canBeReused {
// put in some condition
return YES;
}
@end
@implementation B
-(id)init {
if (self=[super init]) {
// setting the property
self.usefulArray = [NSArray array];
}
return self;
}
@end
当 B 调用 init 时,[super init] 可能会返回一个替换的 A 对象,而当 B 尝试设置该属性(A 没有)时,它不会导致错误吗?
如果这确实会导致错误,我们如何才能以正确的方式实现上述模式?
更新:附加一个更现实的特定问题
这是一个名为 C 的 C++ 类(稍后会解释它的用途)
class C
{
/// Get the user data pointer
void* GetUserData() const;
/// Set the user data. Use this to store your application specific data.
void SetUserData(void* data);
}
说A的目的是充当C的包装器;在A 和C 之间保持一对一的关系非常重要始终。
所以我想出了以下接口和实现
@interface A : NSObject
-(id)initWithC:(C *)c;
@end
@implementation A {
C *_c;
}
-(id)initWithC:(C *)c {
id cu = (__bridge id) c->GetUserData();
if (cu) {
// Bingo, we've got the object already!
if ([cu isKindOfClass:self.class]) {
return (self = cu);
} else {
// expensive operation to unbind cu from c
// but how...?
}
}
if (self=[super init]) {
_c = c;
c->SetUserData((__bridge void *)self);
// expensive operation to bind c to self
// ...
}
return self;
}
@end
这暂时有效。现在我想继承A 所以我想出了B
@interface B : A
@property (nonatomic, strong) NSArray *usefulArray;
@end
现在出现了一个问题,因为A 不知道如何正确取消绑定实例。所以我只好把上面的代码修改成
@interface A : NSObject {
C *_c;
}
-(id)initWithC:(C *)c;
-(void) bind;
-(void) unbind;
@end
@implementation A
-(id)initWithC:(C *)c {
id cu = (__bridge id) c->GetUserData();
if (cu) {
// Bingo, we've got the object already!
if ([cu isKindOfClass:self.class]) {
return (self = cu);
} else {
NSAssert([cu isKindOfClass:[A class]], @"inconsistent wrapper relationship");
[(A *)cu unbind];
}
}
if (self=[super init]) {
_c = c;
c->SetUserData((__bridge void *)self);
[self bind];
}
return self;
}
-(void) bind {
//.. do something about _c
}
-(void) unbind {
// .. do something about _c
_c = nil;
}
@end
现在 B 只需覆盖 bind 和 unbind 即可使其工作。
但是当我想到它时,B 想要做的只是拥有一个额外的数组usefulArray,真的需要这么多工作吗...?编写unbind 只是为了让您的子类在与 C++ 对象的一对一关系中替换您的想法似乎很奇怪(而且效率也很低)。
【问题讨论】:
标签: objective-c subclass init