我正在初始化一个对象的C数组,并设置第一个元素:
id __strong *_objs = (id __strong *)calloc(16,sizeof(*_objs));
_objs[0] = @1;
_count++;然后我使用NSFastEnumeration的以下实现:
- (NSUInteger) countByEnumeratingWithState: (NSFastEnumerationState*)state
objects: (id __unsafe_unretained*)stackbuf
count: (NSUInteger)len
{
NSUInteger size = _count;
NSInteger count;
state->mutationsPtr = (unsigned long *)size;
count = MIN(len, size - state->state);
if (count > 0)
{
IMP imp = [self methodForSelector: @selector(objectAtIndex:)];
int p = state->state;
int i;
for (i = 0; i < count; i++, p++) {
stackbuf[i] = (*imp)(self, @selector(objectAtIndex:), p);
}
state->state += count;
}
else
{
count = 0;
}
state->itemsPtr = stackbuf;
return count;
}不幸的是,当我运行它时,它与EXC_BAD_ACCESS一起崩溃:
for (id object in array){ // EXC_BAD_ACCESS
NSLog(@"%@",object)
}知道为什么吗?
如果您有CodeRunner,则here是一个可执行版本。
发布于 2012-11-02 05:00:29
问题出在mutationsPtr,它指向您不允许访问的内存地址1(也不是4字节对齐的):
state->mutationsPtr = (unsigned long *)size;将其替换为有效的启动器指针(小心:下面的指针在您的场景中可能没有任何意义,但至少它修复了EXC_BAD_ACCESS):
state->mutationsPtr = (unsigned long *)&_count;发布于 2013-03-13 07:48:51
@Jano以防您想要摆脱在Xcode (4.6)的最新版本中出现的编译器警告
- (NSUInteger) countByEnumeratingWithState: (NSFastEnumerationState*)state
objects: (id __unsafe_unretained*)stackbuf
count: (NSUInteger)len因为它与objects:..stackbuf的原始原型不匹配
- (NSUInteger) countByEnumeratingWithState: (NSFastEnumerationState*)state
objects: (__autoreleasing id *)stackbuf
count: (NSUInteger)len请参阅Automatic Reference Counting: Error with fast enumeration中的托德·莱曼斯回答
https://stackoverflow.com/questions/13184961
复制相似问题