gpt4 book ai didi

objective-c - 访问子类实例

转载 作者:行者123 更新时间:2023-12-03 17:42:40 24 4
gpt4 key购买 nike

我有一个类,其中包含不同对象的 NSArray 实例变量,我知道应该从同一个父类(super class)继承。我的问题是如何从另一个类(其 Controller )访问实例变量和方法,同时确保数组的内容仅包含属于某个类的子类的对象?我尝试实现一个最小协议(protocol)并将数组中的对象引用为类型 id(id *) 但这不会让我访问该对象的任何实例变量或方法数组中的类(这是正确的)。在目标文件中

NSArray* components; // contains subclasses of component

在 Controller 文件中

subclassofClassObject* object; 

是否有 subclassOf 函数、宏、typedef ...等或解决方法,以便我可以从 Controller 的子类引用对象子类中组件的子类。即替换 subclassofClass 的东西。

最佳答案

我建议首先考虑你的架构设计。您可以尝试将逻辑移至子类实现中:

@interface BaseClass: NSObject {
}
...
- (void) doMySuperImportantStuff: (id)data;
@end

@implementation BaseClass
...
- (void) doMySuperImportantStuff: (id)data
{
// basic implementation here, or common actions for all subclasses
NSLog(@"BaseClass is here");
}
@end


@interface ClassA: BaseClass
{
NSInteger i;
}
...
@end

@implementation ClassA
...
- (void) doMySuperImportantStuff: (id)data
{
// some specific stuff
NSLog(@"ClassA is here, i=%d", i);
}
@end


@interface ClassB: BaseClass
{
NSString *myString;
}
...
@end

@implementation ClassB
...
- (void) doMySuperImportantStuff: (id)data
{
// another specific stuff
NSLog(@"ClassB is here, myString = %@", myString);
}
@end

// client code example
....
NSArray *list = ...; // list of instances of the subclasses from BaseClass
for(BaseClass *item in list) {
[item doMySuperImportantStuff: userData];
}

关于objective-c - 访问子类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8613578/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com