3
如何在NSFastEnumerationState
的額外數組中安全地存儲幾個對象實例?如何在ARC下的countByEnumeratingWithState內安全地存儲對象?
我希望這些項目在循環運行時保留,然後在循環完成時釋放。
- (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;
}
這裏是NSFastEnumerationState
的定義,從蘋果公司的頭:
typedef struct {
unsigned long state;
id __unsafe_unretained *itemsPtr;
unsigned long *mutationsPtr;
unsigned long extra[5];
} NSFastEnumerationState;
我很驚訝,因爲這些元素默認是很長的。將它們塑造成一個指針似乎已經相當冒險了 - 希望在沒有其他機制的情況下保留指定給它們的任何對象似乎都是不可能的。有趣的問題,因此,+1:D – Till
是的,我的AR轉換(昨天完成)是天真的,我假設我將不得不添加自己的機制。我希望有人比我更瞭解這個。:) –
我已經添加了'NSFastEnumerationState'的定義。 –