正在将对象添加到NSMutableArray,尝试在UITableView上重新加载数据,但未显示新对象.:(



我已经成功地设置了一个UITableView,它从数组中提取其单元格标签。我想做的是向该数组添加一个对象,然后重新加载UITableView,这样它就会显示新对象并创建一个新单元格。不幸的是,我没有运气。

我知道这可能是我在代码中做的非常愚蠢的事情,但有人能告诉我哪里出了问题吗?以下是我目前正在使用的:

这是我的全部。h:

@interface crastinatrViewController : UIViewController <UITableViewDataSource, UITableViewDelegate> {
NSMutableArray *tasksList;
UIView *addtaskview;
}
@property (strong, nonatomic) IBOutlet UITableView *mainTableView;
@property (nonatomic, retain) NSMutableArray *tasksList;
@property (strong, nonatomic) IBOutlet UITextField *taskName;
- (IBAction)addTask:(id)sender;
- (IBAction)startaddTask:(id)sender;
@end

和我的整个.m:

@interface crastinatrViewController ()
@end
@implementation crastinatrViewController
@synthesize mainTableView;
@synthesize tasksList;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
tasksList = [[NSMutableArray alloc] initWithObjects:nil];
self.mainTableView.delegate = self;
self.mainTableView.dataSource = self;
[self.taskName becomeFirstResponder];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSInteger rows = [[self tasksList] count];
NSLog(@"rows is: %d", rows);
return rows;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *contentForThisRow = [[self tasksList] objectAtIndex:[indexPath row]];
static NSString *CellIdentifier = @"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
// Do anything that should be the same on EACH cell here.  Fonts, colors, etc.
}
// Do anything that COULD be different on each cell here.  Text, images, etc.
[[cell textLabel] setText:contentForThisRow];
return cell;}
-(IBAction)startaddTask:(id)sender {
addtaskview = [self.storyboard instantiateViewControllerWithIdentifier:@"addTaskView"];
[self presentViewController:addtaskview animated:YES completion:nil];

}
- (IBAction)addTask:(id)sender {
[tasksList addObject:self.taskName.text];
[self dismissViewControllerAnimated:YES completion:nil];
[mainTableView reloadData];
}
@end

请确保已完成taskList数组的初始化。类似于"tasksList=[[NSMutableArray alloc]init]"。

你试过吗

[self dismissViewControllerAnimated:YES completion:^{
[mainTableView reloadData];
}];

此外,放置断点并检查在调用reloadData时是否调用了TableView Delegate和DataSource方法。

我想,你是硬编码的行数。请检查部分,它将是-

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

最新更新