Bob
Bob

Reputation: 13

NSMutableArray: How do I fix this 'EXC_BAD_ACCESS' code?

I am making an OpenGL Application but I get an EXC_BAD_ACCESS message.

Here is my code:

//(draw function only, ask if you need more)
//objects: array of triangles/quads
//Triangle/Quad3D: should be obvious, I like OOP
//PS this is in a 'Composite Object' class
- (void)draw {
    //NSLog(@"%@",objects);
    NSMutableArray *quad, *tri;
    quad =  [NSMutableArray arrayWithCapacity:0];
    tri =   [NSMutableArray arrayWithCapacity:0];
    NSEnumerator *e = [objects objectEnumerator];
    id object;
    while (object = [e nextObject]) {
        if ([object isKindOfClass:[Triangle3D class]]) {
            [tri addObject:(Triangle3D *)object];
        } else if ([object isKindOfClass:[Quad3D class]]) {
            [quad addObject:(Quad3D *)object];
        }
    }
    NSLog(@"%d",[tri count]);
    NSLog(@"%d",[quad count]);
    [quad release];
    [tri release];
    [e release];
}

Upvotes: 0

Views: 2178

Answers (1)

Jonah
Jonah

Reputation: 17958

You are releasing objects which you do not own because they are autoreleased as per the naming conventions given in http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html

You take ownership of an object if you create it using a method whose name begins with “alloc” or “new” or contains “copy” (for example, alloc, newObject, or mutableCopy), or if you send it a retain message.

+arrayWithCapacity: does not begin with "alloc" or "new" and does not contain "copy" so you should not release the object it returns unless you explicitly retained that object.

Upvotes: 14

Related Questions