我使用core data
作爲我的數據庫。在我的UITableView
裏面,我有一個按鈕來添加項目,但在這一刻我只用它來添加名稱。但我添加的名稱不會顯示在桌面上。 我認爲我的問題是我需要重新填充我的projectArray,我該如何以及在哪裏做。 這裏是我的代碼:TableView不顯示單元格內容
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [_projectArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
Project* project = _projectArray[indexPath.row];
static NSString *cellID = @"TableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
cell.textLabel.text = project.name;
cell.detailTextLabel.text = @"prooo";
self.tableView.delegate = self;
self.tableView.dataSource = self;
return cell;
}
這裏是我的按鈕代碼:
- (IBAction)addProjectButton:(id)sender {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Enter new project name."
message:nil
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"Ok", nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[alert show];
UITextField *textField = [alert textFieldAtIndex:0];
textField.placeholder = @"Project Name";
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex != alertView.cancelButtonIndex) {
UITextField *field = [alertView textFieldAtIndex:0];
AppDelegate *delegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = [delegate managedObjectContext];
NSManagedObject *object =[NSEntityDescription insertNewObjectForEntityForName:@"Project" inManagedObjectContext:context];
[object setValue:field.text forKey:@"name"];
NSError *error;
[context save:&error];
if (![context save:&error]) {
NSLog(@"Whoops %@ %@", error, [error localizedDescription]);
}
[self.tableView reloadData];
} else {
NSLog(@"cancel");
}
}
這裏是我的viewWillAppear中的代碼,我在那裏獲取信息:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:nil];
AppDelegate *delegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = [delegate managedObjectContext];
//load project
NSFetchRequest *fetch = [[NSFetchRequest alloc]init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Project" inManagedObjectContext:context];
[fetch setEntity:entity];
NSError *error;
_projectArray = [context executeFetchRequest:fetch error:&error];
}
你在哪裏設置tableView的數據源和委託? – vikingosegundo
也應該從提取請求中評估錯誤對象。 – vikingosegundo