初始化从应用程序启动引用的视图控制器

时间:2010-06-24 17:37:15

标签: iphone objective-c cocoa-touch

我的数据存储在视图控制器的成员变量(NSArray)中。我遇到的问题是我的数据是在应用程序启动时从数据库加载的,但是NSArray直到稍后才初始化,所以addObject调用默默地失败。

我已经尝试在我的视图控制器(SafeTableViewController)的init,initWithNibName,viewWillAppear和viewDidLoad方法上放置断点,但是在addObject调用之前它们都没有捕获。我假设实际的视图控制器已初始化,因为当我在调试器中观察它时它有一个非零地址,但是当调用addObject时,NSArray的地址为0x0。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
    databaseName = @"DubbleDatabase.sql";

    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [documentPaths objectAtIndex:0];
    databasePath = [documentsDir stringByAppendingPathComponent:databaseName];

    [self checkAndCreateDatabase];

    [self readSafeItemsFromDatabase ];

    // Add the tab bar controller's current view as a subview of the window
    [window addSubview:tabBarController.view];
    [window makeKeyAndVisible];

    return YES;
}
- (void) readSafeItemsFromDatabase {
    // some code skipped here, but basically: open sqlite3 database, iterate through rows

            while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
                // read database, get data fields out

                SafeItem *safeItem = [[SafeItem alloc] initWithName:aName price:aPrice category:aCategory];

                [safeTableViewController addItemToSafe: safeItem]; // PROBLEM HERE

                [safeItem release];
            }
    }
    sqlite3_close(database);
}

在SafeTableViewController.m中:

- (void) addItemToSafe : (SafeItem*) newSafeItem {
    [self.safeItems addObject: newSafeItem]; 
}

// I put a breakpoint on this, but it does not hit.  i.e. safeItems is not initialized when addObject is called on it.
-(id) init {
    if(self = [super initWithNibName:@"SafeTableViewController" bundle:nil]){
        self.safeItems = [[NSMutableArray alloc] init];
    }
    return self;
}
编辑:想到解决这个问题的方法。仍然很好奇:什么时候是init和/或initWithNibName被调用?这是建议的解决方案:

- (void) addItemToSafe : (SafeItem*) newSafeItem {
    if(self.safeItems == nil){
        self.safeItems = [[NSMutableArray alloc] init];
    }
    [self.safeItems addObject: newSafeItem]; 
}

2 个答案:

答案 0 :(得分:1)

问题是您不应该将数据存储在视图控制器中。创建一个模型对象(例如SafeItemManager)来保存数据并将视图控制器指向该数据。

答案 1 :(得分:1)

如何设置SafeTableViewController的实例?通过代码?通过笔尖?

-(id) init不是指定的初始化程序。

您可能想要使用

- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle {
    if(self = [super initWithNibName:nibName bundle:nibBundle]){
        self.safeItems = [[NSMutableArray alloc] init];
    }
    return self;
}

或在其他地方初始化,即在viewDidLoad