2011-06-24 50 views
0

我試圖創建一個簡單的應用程序,其中我有一個應該顯示文件內容的TableView。我在IB中創建了一個表視圖,並將它的代表和數據源拖到文件的所有者,我手動創建了一個包含2個項目的1個數組的.plist文件。無法將文件的內容從.plist文件中獲取到數組中

在我的TableViewController.h我已經聲明瞭一個數組。

NSArray * posts; 

我在執行文件我已經宣佈了UITableViewDataSource這樣所需的方法:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    NSLog(@"Returning num sections"); 
    return posts.count; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    // create a cell 
    UITableViewCell * post = [[UITableViewCell alloc]  
    initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"post"]; 

    // fill it with content 
    post.textLabel.text = [posts objectAtIndex:indexPath.row]; 

    // return it 
    return post; 
} 

而且在我的ViewController「viewDidLoad中」的方法我嘗試我的文件的內容添加到了「的帖子'array like this:

- (void)viewDidLoad 
{ 

    NSString * postFile = [[NSBundle mainBundle] pathForResource:@"Posts" ofType:@"plist"]; 
    posts = [[NSArray alloc] initWithContentsOfFile:postFile]; 

    NSLog(@"%@", postFile); 
    NSLog(@"%i", posts.count); 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view from its nib. 
} 

NSLog(@「%i」,posts.count);返回0,儘管我已將值添加到我的.plist文件。並且表格視圖中不顯示任何內容。

建議如何解決這個問題將不勝感激。

+0

和'viewDidLoad'第一個日誌的輸出是什麼?它不是零嗎? –

+0

當您構建應用程序時,您的Posts.plist是否已預填充,或者您是否在向其動態添加內容? – Joe

+0

我手動創建它並添加了初始值,但我將保存用戶職位。我將該文件放入我的Xcode(4)項目的「支持文件」目錄中。 – Anders

回答

0

好吧,它看起來像Xcode 4創建與詞典plist,因爲它是根類型。如果你想使用數組,你必須在另一個文本編輯器中打開.plist文件(可能也可以在Xcode中使用)並將<字典> </dict />更改爲<數組>。另外,根本不需要使用數組。這也工作:

// Changed my array to a dictionary. 
NSDictionary * posts; 

// Get the cell text. 
NSString * cellText = [[NSString alloc] initWithFormat:@"%i", indexPath.row]; 
// fill it with content 
post.textLabel.text = [posts valueForKey:cellText]; 
2

我想你需要重新加載你的表後,你已經加載你的postFile NSArray。如果您的視圖控制器是一個UITableViewController,嘗試添加下面的代碼行到你viewDidLoad方法的末尾:

[self.tableView reloadData]

(在一個不相關的音符,你也應該讓你調用父類第一你在viewDidLoad方法中做的事情,因此xcode模板給你的評論。)

編輯:計數問題。
我覺得你的調試也有問題。 count不是NSArray的屬性,因此您不能對它使用點語法。您應該向您的NSArray實例發送消息,即[posts count]

+0

感謝您的回答,我的視圖控制器是一個正常的UIViewController,因此添加[self.tableView reloadData]不起作用。我得到了錯誤:在'PostsTableViewController *' – Anders

+0

類型的對象上找不到屬性tableView我會查看UITableViewController上的指南,因爲聽起來你會從使用一個而不是使用UIViewController獲益。基本上,你想調用你正在使用的UITableView實例的'reloadData',所以你需要確保你有它作爲一個實例變量(UITableViewController爲你做這個)。 –

+0

我已經更改爲UITableViewController,但NSLog(@「%i」,posts.count);仍然返回0. – Anders