如何在ARC下的countByEnumeratingWithState中安全地存储对象?

时间:2012-10-12 20:36:12

标签: ios automatic-ref-counting fast-enumeration

如何在NSFastEnumerationState的额外数组中安全存储几个对象实例?

我想在循环运行时保留这些项,然后在循环完成时释放。

- (NSUInteger)countByEnumeratingWithState: (NSFastEnumerationState *)state
                                  objects: (__unsafe_unretained id *)stackbuf
                                    count: (NSUInteger)len {
    unsigned long days = 0;
    id current = nil;
    id components = nil;
    if (state->state == 0)
    {
        current = [NSCalendar currentCalendar];
        state->mutationsPtr = &state->extra[0];
        components = [current components: NSDayCalendarUnit fromDate: _startDate toDate: _endDate options: 0];
        days = [components day];
        state->extra[0] = days;
        state->extra[1] = (uintptr_t)(__bridge void *)current;
        state->extra[2] = (uintptr_t)(__bridge void *)components;
    } else {
        days = state->extra[0];
        current = (__bridge NSCalendar *)(void *)(state->extra[1]);
        components = (__bridge NSDateComponents *)(void *)(state->extra[2]);
    }
    NSUInteger count = 0;
    if (state->state <= days) {
        state->itemsPtr = stackbuf;
        while ( (state->state <= days) && (count < len) ) {
            [components setDay: state->state];
            stackbuf[count] = [current dateByAddingComponents: components toDate: _startDate options: 0];
            state->state++;
            count++;
        }
    }
    return count;
}

以下是来自Apple的标题NSFastEnumerationState的定义:

typedef struct {
    unsigned long state;
    id __unsafe_unretained *itemsPtr;
    unsigned long *mutationsPtr;
    unsigned long extra[5];
} NSFastEnumerationState;

1 个答案:

答案 0 :(得分:1)

史蒂芬,

为什么要尝试使用C语言结构来保存这些项目而不是仅仅在要为其构建枚举器的类中将它们设为私有ivars?让他们成为伊莎,问题就不存在了。

安德鲁