自定义NSFastEnumeration方法?

时间:2013-09-16 11:38:27

标签: objective-c containers nsfastenumeration

我有一个容器类,用于将其数据存储在字典中

我想枚举对象而不是键。

现在我有这样的代码

-(NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(__unsafe_unretained id [])buffer count:(NSUInteger)len
{
    return [self.container countByEnumeratingWithState:state objects:buffer count:len]; // this isn't working as container is dictionary
}

-(myobject *)objectAtIndex:(int)number // this is the method to retrieve a specific object
{
    int i = 0;
    for(id key in self.container) {
        if (number == i) {
            id value = [self.container objectForKey:key];
            return value;
        }
        else i++;
    }
    return nil;
}

1 个答案:

答案 0 :(得分:2)

为什么不直接使用-allValues属性:

-(NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(__unsafe_unretained id [])buffer count:(NSUInteger)len
{
    return [self.container.allValues countByEnumeratingWithState:state objects:buffer count:len];
}

此外,NSDictionary未订购的容器,因此您的-objectAtIndex:方法毫无意义。