objective-c - isMemberOfClass 作为管理对象的一种方式

标签 objective-c ios

我有一个 NSArray 包含 (id) 6 种 UIModels:按钮、图像等..

它们都是我的基本模型的子类。例如:

MyButtonModel : MyUIModel : NSObject

所以我想在我的 View 中以不同的方式处理它。

for(int i = 0 ; i < [_screenModel.MUIElements count] ; i++)
{
    id UIElement = [_screenModel.MUIElements objectAtIndex:i];
    [self checkWhatKindOfUIElement:UIElement];

}

-(void)checkWhatKindOfUIElement:(id)MUIElement;
{
    if([MUIElement isMemberOfClass:[ButtonModel class]])
        NSLog(@"button");
}

所以我当然可以那样做,但是我必须检查它 6 ifs 吗?没有别的办法吗?

最佳答案

是的,您必须使用 6 个 ifs 检查每个派生类,但我认为您没有使用已经建立的继承模型的强大功能。为什么不以您喜欢的任何方式使用该对象,也许添加方法来公开功能;例如:

for (int i = 0 ; i < [_screenModel.MUIElements count] ; i++)
{
    MyUIModel *UIElement = [_screenModel.MUIElements objectAtIndex:i];

    [UIElement doThingWithString:@"string"];

    if ([UIElement respondsToSelector:@selector(optionalMethod:)])
    {
        [UIElement optionalMethod:12];
    }

    if ([UIElement isCapableOfAnything])
    {
        [UIElement doAnything];
    }
}

关于objective-c - isMemberOfClass 作为管理对象的一种方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11560627/

相关文章:

ios - 从 UISearchDisplayController 转换 ==> UISearchController 无法显示搜索栏

objective-c - Xcode 警告缺少协议(protocol)定义,即使使用了@protocol

ios - 轻量级数据迁移

ios - 我的 NSUserDefaults 代码不工作

iphone - iOS 中的并行下载

android - Google Maps API,我需要购买吗?

iphone - 打开模态视图时的 EXC_BAD_ACCESS

ios - 无法使用 objective-c 将行插入到 sqlite 数据库中

ios - 调整 UIImageView 的大小以恰好在 UITextView 中一行结束的下方和一行开始的上方

ios - 查找索引路径的编号