2011-03-07 25 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