0

在這種情況下這將如何工作?我創建了一個NSMutabeArray * dataSource;在我的.h文件中,但得到一堆錯誤:如何用Button添加單元格?

「RootViewController.m:錯誤:語義問題:房產‘數據源’上輸入‘* RootViewController的’對象找不到」

RootViewController.h

#import <UIKit/UIKit.h> 

@interface RootViewController : UITableViewController { 
NSMutableArray *dataSource; 
} 

@property (nonatomic,retain) NSMutableArray *dataSource; 
- (IBAction)addButton:(id)sender; 

@end 

RootViewController.m

#import "RootViewController.h" 

@implementation RootViewController 
@synthesize dataSource; 

- (void)viewDidLoad 
{ 
[super viewDidLoad]; 
self.dataSource = [NSMutableArray arrayWithCapacity:1]; 
//adds right bar button. 
UIBarButtonItem *addButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(add:)]; 
self.navigationItem.rightBarButtonItem=addButton; 
[addButton release]; 

} 

-(void)addButton:(id)sender{ 
[self.dataSource addObject:@"New Item"]; 
NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:[self.dataSource count] inSection:0]; 
[self.dataSource insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade]; 
} 

回答

1

一些記憶大師無疑將能告訴你爲什麼@synthesize和可變數組和字典(及組合,大概)不玩好一起。我所知道的是,明確地初始化可變數組和一切都會好起來:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    self.dataSource = [NSMutableArray arrayWithCapacity:1]; 

    //adds right bar button. 
    UIBarButtonItem *addButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(add:)]; 
    self.navigationItem.rightBarButtonItem=addButton; 
    [addButton release]; 
} 

,當然,在dealloc中釋放出來。

+0

有沒有更好的方法來做到這一點? – Jason 2011-03-17 18:30:55

+0

NSFetchedResultsController。 – 2011-03-17 20:33:21

0

您尚未創建的.h文件中財產和您使用的數據源的變量與自我。 請用dataSource替換self.dataSource或爲其創建屬性。

@property (nonatomic,retain) NSMutableArray *dataSource; 

和綜合.m文件

@synthesize dataSource; 
+0

仍然有錯誤。我正在使用一個tableview模板,並使用一個group table查看錶。基本上我只想點擊右側導航欄上的「+」按鈕並添加一個單元格。我不得不添加一個帶有代碼的按鈕,因爲您無法更改表格的IB選項以外的RootViewController.xib。也許這會更清楚些,謝謝你的快速回答,但它不起作用。也許我給出的信息將會幫助更多。 – Jason 2011-03-17 16:53:41

+0

你原來的問題與你在這裏的評論有很大的不同......你可能想編輯你的問題來澄清。你是否仍然得到你在問題中列出的同樣的錯誤? – GendoIkari 2011-03-17 17:29:13

+0

我的問題是如何添加按鈕的單元格。這就是我想要做的......但由於我不能通過IB添加一個導航按鈕到RootViewController.xib,所以我必須添加代碼。所以試圖弄清楚如何讓我從代碼中添加的按鈕添加一個單元格到組表中。 – Jason 2011-03-17 18:17:10

相關問題