Created
November 1, 2012 19:59
-
-
Save janodev/3996072 to your computer and use it in GitHub Desktop.
NSFastEnumeration over a C array crashing with BAD_ACCESS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
@interface Array : NSObject <NSFastEnumeration> { | |
id __strong *_objs; | |
NSUInteger _count; | |
} | |
@end | |
@implementation Array | |
-(id)init { | |
self = [super init]; | |
if (self){ | |
_objs = (id __strong *)calloc(16,sizeof(*_objs)); | |
} | |
return self; | |
} | |
-(void) addObject:(id)object { | |
_objs[_count] = object; | |
_count++; | |
} | |
-(id) objectAtIndex:(NSUInteger)index { | |
return _objs[index]; | |
} | |
- (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; | |
} | |
@end | |
int main(int argc, char *argv[]) { | |
@autoreleasepool { | |
Array *array = [Array new]; | |
[array addObject:@1]; | |
for (id object in array){ // BAD_ACCESS ! | |
NSLog(@"%@",object); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Solved at http://stackoverflow.com/questions/13184961/