views:

26

answers:

1

Hello!

I have made a subclass of NSObject that is meant to be the model of my application. The class has a few methods and on instance primitive array as such:

@interface Cube : NSObject {
    int cubeState[5][2][2];
}

- (void)printContent;

@end

@implementation Cube


- (id)init {
    if (self = [super init]) {
        for (int i=0; i<=5; i++) {
            for (int j=0; j<=2; j++) {
                for (int k=0; k<=2; k++) {
                    cubeState[i][j][k] = i;
                }
            }
        }
    }
    return self;
}


- (void)printContent {
    for (int i=0; i<=5; i++) {
        for (int j=0; j<=2; j++) {
            for (int k=0; k<=2; k++) {
                NSLog(@"[%d] [%d] [%d] = %d", i, j, k, cubeState[i][j][k]);
            }
        }
    }
}

@end

This works fine if instanciated from the delegate as such:

#include "Cube.h"

@implementation CubeAppDelegate

@synthesize window;


- (void)applicationDidFinishLaunching:(UIApplication *)application {
    Cube *cube = [[Cube alloc] init];
    [cube printContent];
    [cube release];

    [window makeKeyAndVisible];
}

However, the application crashes if I try to create a subclass of UIViewController with a Cube *cube property and later try to access the Cube instance object through the view controller's property as such:

@interface CustomController : UIViewController {
    Cube *cube;
}

@property (nonatomic, retain) Cube *cube;

@end

@implementation CustomController

@synthesize cube;

- (void)dealloc {
    [cube release];
    [super dealloc];
}
@end

and in the delegate:

- (void)applicationDidFinishLaunching:(UIApplication *)application {
    viewController = [[CustomController alloc] 
                        initWithNibName:@"MainView" bundle:nil];
    viewController.cube = [[[Cube alloc] init] autorelease];

    [viewController.cube printContent]; // Application crashes here
}

Any ideas?

+2  A: 

(1)

int cubeState[5][2][2];
...
    for (int i=0; i<=5; i++) {
        for (int j=0; j<=2; j++) {
            for (int k=0; k<=2; k++) {

Your cube's size is just 5x2x2, so the max index is only [4, 1, 1], but you're obviously accessing stuff beyond this limit. Try to change the <= into <.

(2)

- (void)init {

An -init must return id. Since you're returning void, the statement

[[[Cube alloc] init] autorelease];

could return some messed up stuffs.

And of course

- (id)printContent;

This should return void instead.

KennyTM
KennyTM! Thank you so very much, you nailed it. I thought the index when declaring the size of the array was the maximum index and not the number of items. As far as the id/void is concenred, yes, yes, absolutely, I typed some dummy function really quick and that went over my head. In any case, thank you!
FatalMojo