2011-03-07 27 views
-1

我试图从不同的类文件访问和更改数组。当使用NSLog时,我得到(null)的结果。下面是我的代码:从不同的类文件获取并编辑NSMutableArray

RootViewController.h

NSMutableArray *listOfItems; 
@property (nonatomic, retain) NSMutableArray *listOfItems; 

RootViewController.m

@synthesize listOfItems; 
listOfItems = [[NSMutableArray alloc] init]; 
[listOfItems addObject:@"One"]; 
[listOfItems addObject:@"Two"]; 
[listOfItems addObject:@"Three"]; 

SecondViewController.m

RootViewController *test = [[RootViewController alloc] init]; 
NSLog(@"Results: %@", test.listOfItems); 

我得到了我的控制台以下结果:提前Results: (null)

感谢, 库尔顿

附:显然,我遗漏了一堆代码。我只是试图让它更易于阅读。如果您需要查看其他内容,我会非常乐意发布更多内容。只要问

编辑#1:

我收到数以百计的NSLog消息说是这个样子:

*** __NSAutoreleaseNoPool(): Object 0x4e39020 of class __NSArrayI autoreleased with no pool in place - just leaking 

这是我的初始化代码:

- (id) init { 

//NSLog(@"%@", theUserID); 
// Set up database connection 
NSString *myDB = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"database.db"]; 
database = [[Sqlite alloc] init]; 
[database open:myDB]; 

//Initialize the array. 
listOfItems = [[NSMutableArray alloc] init]; 

// Add to array to display in the tableView 
NSArray *listOfItemsTwo = [database executeQuery:@"SELECT * FROM albums"]; 
for (NSDictionary *rowone in listOfItemsTwo) { 
    NSString *getName = [rowone valueForKey:@"name"]; 
    if (getName != NULL) { 
     [listOfItems addObject:getName]; 
     [getName release]; 
    } 
} 
return self; 

}

回答

1

I猜你逆转RootViewController.m和RootViewController.h片段的权利?

您确保

listOfItems = [[NSMutableArray alloc] init]; 

被调用?也许你可以在那里放置一个断点。

编辑:RootViewController.m和RootViewController.h的顺序已在问题中修复。从代码中上述行的位置问题不清楚。这是一条重要的信息。

EDIT2:init方法的例子。

@implementation RootViewController 
- (id) init 
{ 
    listOfItems = [[NSMutableArray alloc] init]; 
    [listOfItems addObject:@"One"]; 

    return self; 
} 
@end 
+0

是的,谢谢指出。它在'viewDidLoad'中被调用。它确实得到了填充(它在我执行此操作之前显示在我的tableView中)。我应该尝试将它放入“viewWillAppear”吗? – iosfreak 2011-03-07 04:14:33

+1

你应该把它放在init函数中。这就是你在你的行中调用的内容:RootViewController * test = [[RootViewController alloc] init];除非它在init函数中,否则在下一行中将看不到它。 – 2011-03-07 04:16:09

+0

这可能是一个愚蠢的问题 - 但什么是INIT函数?如同任何其他函数一样,init定义为 – iosfreak 2011-03-07 04:37:29