开发者

Unable to access a primitive array inside a custom class from a UIViewController instance

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]) {
     开发者_JAVA百科   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?


(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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜