在自定义类上实现 NSFastEnumeration [英] Implementing NSFastEnumeration on Custom Class
问题描述
我有一个继承自 NSObject 的类.它使用 NSMutableArray 来保存子对象,例如人们使用 NSMutableArray *items 来保存 Person 对象.如何在项目上实现 NSFastEnumerator?
I have a class that inherits from NSObject. It uses an NSMutableArray to hold children objects, e.g. People using NSMutableArray *items to hold Person objects. How do I implement the NSFastEnumerator on items?
我尝试了以下但无效:
@interface People : NSObject <NSFastEnumeration>
{
NSMutableArray *items;
}
@implementation ...
@implementation ...
- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len
{
if(state->state == 0)
{
state->mutationsPtr = (unsigned long *)self;
state->itemsPtr = items;
state->state = [items count];
return count;
}
else
return 0;
}
推荐答案
您没有正确使用 NSFastEnumerationState 结构.请参阅 NSFastEnumeration 协议参考并查看在常量部分查看每个字段的描述.在您的情况下,您应该将 state->mutationsPtr
保留为 nil.state->itemsPtr
应该设置为对象的 C 数组,而不是 NSArray 或 NSMutableArray.您还需要将相同的对象放入作为 stackbuf 传递的数组中.
You are not using the NSFastEnumerationState structure properly. See NSFastEnumeration Protocol Reference and look at the constants section to see a description of each of the fields. In your case, you should leave state->mutationsPtr
as nil. state->itemsPtr
should be set to a C-array of the objects, not an NSArray or NSMutableArray. You also need to put the same objects into the array passed as stackbuf.
但是,由于您使用 NSMutableArray 来包含您正在枚举的对象,您可以将调用转发到该对象:
However, since you are using an NSMutableArray to contain the objects you are enumerating, you could just forward the call to that object:
- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len {
return [items countByEnumeratingWithState:state objects:stackbuf count:len];
}
这篇关于在自定义类上实现 NSFastEnumeration的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!