无法从UIViewController实例访问自定义类中的基本数组

时间:2010-04-06 03:37:05

标签: objective-c arrays class

我已经创建了NSObject的子类,它应该是我的应用程序的模型。该类有一些方法和实例原始数组:

@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

如果从委托中实例化,这可以正常工作:

#include "Cube.h"

@implementation CubeAppDelegate

@synthesize window;


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

    [window makeKeyAndVisible];
}

但是,如果我尝试使用Cube * cube属性创建UIViewController的子类,然后尝试通过视图控制器的属性访问Cube实例对象,应用程序崩溃:

@interface CustomController : UIViewController {
    Cube *cube;
}

@property (nonatomic, retain) Cube *cube;

@end

@implementation CustomController

@synthesize cube;

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

并在代表中:

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

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

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

<强>(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++) {

你的立方体的大小只有5x2x2,所以最大索引只有[4,1,1],但你显然是在访问超出这个限制的东西。尝试将<=更改为<

<强>(2)

- (void)init {

-init必须返回id。由于您正在返回void,因此声明

[[[Cube alloc] init] autorelease];

可以返回一些混乱的东西。

当然

- (id)printContent;

这应该返回void