Ger*_*eri 8 collections iterator casting objective-c ios
我有一个带有一些对象组合的模型类,我不知道为此编写迭代器的最佳方法.要更详细地查看问题,这里是层次结构(半伪代码):
Root类:
MYEntity : NSObject
@property int commonProperty;
@property NSArray *childs; //Childs of any kind.
Run Code Online (Sandbox Code Playgroud)
一些具体的子类:
MYConcreteStuff : MYEntity
@property int number;
MYConcreteThing : MYEntity
@property NSString *string;
Run Code Online (Sandbox Code Playgroud)
并且具有具体集合的根对象:
MYRoot : MYEntity
@property MYEntity *stuff; //Collect only stuff childs here.
@property MYEntity *things; //Collect only thing childs here.
Run Code Online (Sandbox Code Playgroud)
现在我可以为集合编写很酷的成员访问器(在MYEntity中),如:
-(MYEntity*)entityForIndex:(int) index
{
if ([self.childs count] > index)
return [self.childs objectAtIndex:index];
return nil;
}
Run Code Online (Sandbox Code Playgroud)
对于根对象,甚至更酷,良好类型的成员成员访问器.
-(MYConcreteThing*)thingForIndex:(int) index
{
if ([self.things count] > index)
return (MYConcreteThing*)[self.things entityForIndex];
return nil;
}
Run Code Online (Sandbox Code Playgroud)
但是我不知道如何为这样的集合编写一些oneliner迭代器.想要的客户端代码如下:
for (MYConcreteThing *eachThing in myRoot.things)
eachThing.string = @"Success."; //Set "thingy" stuff thanks to the correct type.
Run Code Online (Sandbox Code Playgroud)
我正在考虑使用积木,但可能会有一个更干净的解决方案.任何想法/经验?
我现在继续使用积木,这非常简单.现在我更喜欢枚举这个词.
用于物品的块类型(确保正确的类型):
typedef void (^MYThingEnumeratorBlock)(MYThing *eachThing);
Run Code Online (Sandbox Code Playgroud)
MYRoot中的一个很酷的枚举器方法(不公开集合):
-(void)enumerateThings:(MYThingEnumeratorBlock) block
{
for (MYThing *eachThing in self.things.childs)
block(eachThing);
}
Run Code Online (Sandbox Code Playgroud)
所以客户端代码:
[myRoot enumerateThings:^(MYThing *eachThing)
{
NSLog(@"Thing: %@", eachThing.string);
}];
Run Code Online (Sandbox Code Playgroud)
有一些整洁的宏:
#define ENUMARATE_THINGS myRoot enumerateThings:^(MYThing *eachThing)
[ENUMARATE_THINGS
{
NSLog(@"Thing: %@", eachThing.string); //Cool "thingy" properties.
}];
Run Code Online (Sandbox Code Playgroud)