我正在尝试使用 iPhone SDK 更改使用 nib 创建的对象类。
原因是;直到运行时我才知道我希望 nib 对象是什么类(尽管它们将具有相同的基于 UIView 的超类),并且我不想为每种可能性创建不同的 nib - 因为 .nib 将是除了一个对象的类别之外,每个对象都相同。
我已经成功了,有几种方法,但要么有一些连锁反应,要么不确定我使用的方法有多安全:
方法1:在超类上覆盖alloc,并将ac变量设置为我需要的类:
+ (id) alloc {
if (theClassIWant) {
id object = [theClassIWant allocWithZone:NSDefaultMallocZone()];
theClassIWant = nil;
return object;
}
return [BaseClass allocWithZone:NSDefaultMallocZone()];
}
这很好用,我认为是“合理”安全的,但如果有一个具有正确类的 nib 作为 Nib 中的类标识,或者我自己分配一个子类(不设置“theClassIWant”) - 一个基类的对象被建造。我也不太喜欢覆盖 alloc 的想法......
方法2:在initWithCoder中使用object_setClass(self,theClassIWant)(在超类调用initWithCoder之前):
- (id) initWithCoder:(NSCoder *)aDecoder {
if (theClassIWant) {
// the framework doesn't like this:
//[self release];
//self = [theClassIWant alloc];
// whoa now!
object_setClass(self,theClassIWant);
theClassIWant = nil;
return [self initWithCoder:aDecoder];
}
if (self = [super initWithCoder:aDecoder]) {
...
这也很有效,但并不是所有的子类都必须与超类的大小相同,所以这可能非常不安全!为了解决这个问题,我尝试在 initWithCoder 中释放并重新分配正确的类型,但我从框架中得到以下错误:
“此编码器要求从 initWithCoder 返回替换的对象:”
不太明白这意味着什么!我正在替换 initWithCoder 中的一个对象...
欢迎对这些方法的有效性提出任何意见,或提出改进或替代方案的建议!