2014-10-17 79 views
0

我通過將其保存在nsuserdefaults中從另一個視圖控制器傳遞可變數組。然後我在新的視圖控制器中檢索它,它在nslog中很好。當我的代碼達到numberofrowsinsections時遇到問題。看起來像我的tableview不識別我的數組對象。感謝任何幫助,因爲我是編碼方面的新手。未在我的表格視圖中顯示的數組

#import "ViewController.h" 
#import "RecordView.h" 
#import "bookCellTableViewCell.h" 

@interface ViewController() 

@end 

@implementation ViewController 
@synthesize arr; 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 


    NSMutableArray *arr = [[NSMutableArray alloc]init]; 
    arr = [[NSUserDefaults standardUserDefaults] valueForKey:@"projects"]; 
    NSLog(@"arr%@", [arr description]); 

    #pragma mark - Table view data source 
    // Do any additional setup after loading the view, typically from a nib. 
} 

- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return [arr count]; 
} 


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

    //static NSString *CellIdentifier = @"Cell"; 
    bookCellTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ToBook"]; 
    if(cell != nil) 
    { 


     cell.songTitle.text = [arr objectAtIndex:indexPath.row]; 
     testLabel.text = @"Hello"; 
    } 

    return cell; 
} 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ 

    UITableViewCell *cell = [bookView cellForRowAtIndexPath:indexPath]; 

} 


@end 

回答

1

這是一個範圍問題:

你已經宣佈你的數據源中viewDidLoad

NSMutableArray *arr = [[NSMutableArray alloc]init]; 

這是不正確的,你的數據源應該是一個屬性,或者至少類範圍的變量。

您應該初始化它在viewDidLoad但在類級別上聲明它。

看起來你已經有一個名爲arr的屬性了,智能編譯器應該警告你模糊不清。

爲了解決這個問題只是刪除了這一行的NSMutableArray *一部分,就像這樣:

arr = [[NSMutableArray alloc]init]; 

您還濫用NSUserdefault這並不意味着通過控制器之間的數據,它更適合用於保存基本用戶設置值。

要傳遞數據,只需在提供屬性之前設置ViewController屬性的值。

+0

感謝您的幫助,但我無法使其工作。我能夠將我的數組傳遞給下一個Viewcontroller的唯一方法是使用nsuserdefaults或創建一個單例。當使用單例時,我能夠nslog數組,這意味着該對象正在被傳遞,但我現在正在收到「nsdictionary長度無法識別的選擇器錯誤」。 – 2014-10-17 20:03:58

+0

對不起最後的評論,但我的問題已解決,謝謝!這是一個偉大的單身教程http://x-code-tutorials.com/2012/06/04/pass-nsobjects-and-values-between-view-controllers/ – 2014-10-17 20:16:40

+0

@MichaelBain只是告訴我你是如何調用viewController的,我們對此進行分類 – meda 2014-10-17 20:16:51