Fastenumeration implementation

110 views Asked by At

I am trying to implement the countByEnumeratingWithState method in my objective-c class (say MyClass In this method I do an

MyOtherClass *cl = [[MyOtherClass alloc] init];
buffer[count++] = cl;

The reason why I have to allocate objects on the fly is because those objects are stored 'elsewhere'. However, when using this method from an application, it will crash:

for (const MyOtherClass *cl in myClassObj){
    NSLog(@"obj: %@", cl.description);
}

The reason for this is most likely that ARC throws away my MyOtherClass object in countByEnumeratingWithState because the buffer is 'unretained'. How can I make sure the MyOtherClass object 'retains' ?

More relevant information:

  • thread #4: tid = 0x5ca941, 0x0000000101a4cf8b libobjc.A.dylibobjc_msgSend + 11, stop reason = EXC_BAD_ACCESS (code=EXC_I386_GPFLT) frame #0: 0x0000000101a4cf8b libobjc.A.dylibobjc_msgSend + 11
1

There are 1 answers

2
Greg On

Why do you use const keyword? Const let you allocate object just for initialization and after then throw exception when you want to try change it. Try that:

for (MyOtherClass *cl in myClassObj){
    NSLog(@"obj: %@", cl.description);
}