【发布时间】:2012-09-23 04:11:46
【问题描述】:
我有一个包含一些对象组合的模型类,但我不知道为此编写迭代器的最佳方法。要更详细地查看问题,这里是层次结构(半伪代码):
一个根类:
MYEntity : NSObject
@property int commonProperty;
@property NSArray *childs; //Childs of any kind.
一些具体的子类:
MYConcreteStuff : MYEntity
@property int number;
MYConcreteThing : MYEntity
@property NSString *string;
还有一个带有具体集合的根对象:
MYRoot : MYEntity
@property MYEntity *stuff; //Collect only stuff childs here.
@property MYEntity *things; //Collect only thing childs here.
现在我可以为集合(在 MYEntity 中)编写很酷的成员访问器,例如:
-(MYEntity*)entityForIndex:(int) index
{
if ([self.childs count] > index)
return [self.childs objectAtIndex:index];
return nil;
}
还有更酷的、用于根对象的类型转换成员访问器。
-(MYConcreteThing*)thingForIndex:(int) index
{
if ([self.things count] > index)
return (MYConcreteThing*)[self.things entityForIndex];
return nil;
}
但我不知道如何为此类集合编写一些单行迭代器。 想要的客户端代码类似于:
for (MYConcreteThing *eachThing in myRoot.things)
eachThing.string = @"Success."; //Set "thingy" stuff thanks to the correct type.
我正在考虑使用积木,但可能会有更简洁的解决方案。 有什么想法/经验吗?
【问题讨论】:
标签: objective-c ios collections casting iterator