gpt4 book ai didi

objective-c - 如何为属性的集合属性编写我自己的迭代器(使用正确的类型转换)?

转载 作者:可可西里 更新时间:2023-11-01 03:09:09 25 4
gpt4 key购买 nike

我有一个包含一些对象组合的模型类,但我不知道为此编写迭代器的最佳方法。要更详细地查看问题,这里是层次结构(半伪代码):

根类:

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.

我正在考虑使用 block ,但可能有更简洁的解决方案。有什么想法/经验吗?

最佳答案

现在我将继续使用积木,这非常简单。现在我更喜欢枚举这个词。

事物枚举的 block 类型(确保类型正确):

typedef void (^MYThingEnumeratorBlock)(MYThing *eachThing);

MYRoot 中 Things 的一个很酷的枚举器方法(不公开集合):

-(void)enumerateThings:(MYThingEnumeratorBlock) block
{
for (MYThing *eachThing in self.things.childs)
block(eachThing);
}

因此客户端代码如下:

[myRoot enumerateThings:^(MYThing *eachThing)
{
NSLog(@"Thing: %@", eachThing.string);
}];

用一些简洁的宏:

#define ENUMARATE_THINGS myRoot enumerateThings:^(MYThing *eachThing)

[ENUMARATE_THINGS
{
NSLog(@"Thing: %@", eachThing.string); //Cool "thingy" properties.
}];

关于objective-c - 如何为属性的集合属性编写我自己的迭代器(使用正确的类型转换)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12549667/

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