为什么我的NSMutableArray对象不会立即添加到UITableView?

时间:2011-11-02 07:50:16

标签: iphone objective-c ios xcode nsmutablearray

我有一个带有对象的NSMutableArray,我使用以下代码从UITableView添加/删除对象。它只能在关闭并重新启动应用程序后才能运行,而不是立即启动。为什么是这样?这是我的代码(maincelltext是单元格中的标题,subtitlecelltext是副标题):

maincelltext = [[NSMutableArray alloc] init];
subtitlecelltext = [[NSMutableArray alloc] init];

[maincelltext addObject:@"TITLE"];
[subtitlecelltext addObject:@"SUBTITLE TEST"];

编辑:这是我的UITableView代码:

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

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}

cell.textLabel.font = [UIFont fontWithName:@"HelveticaBold" size:16.0];

cell.textLabel.adjustsFontSizeToFitWidth = YES; 
cell.textLabel.numberOfLines = 1;

// Configure the cell.
UIImage *cellImage = [UIImage imageNamed:@"warning.png"];
CGRect cropRect = CGRectMake(0.0, 0.0, 12.0, 12.0);
CGImageRef croppedImage = CGImageCreateWithImageInRect([cellImage CGImage], CGRectMake(0.0f,0.0f,cellImage.size.width,cellImage.size.height));
UIImageView *myImageView = [[UIImageView alloc] initWithFrame:cropRect];
[myImageView setImage:[UIImage imageWithCGImage:croppedImage]]; 
CGImageRelease(croppedImage);
[self.view addSubview:myImageView];

cell.imageView.image = cellImage;

NSString *subjectString = [maincelltext objectAtIndex: [indexPath row]];

cell.textLabel.text = subjectString;

NSString *subtitle = [subtitlecelltext objectAtIndex: [indexPath row]];

cell.detailTextLabel.text = subtitle;

if(maincelltext.count == 0){

    NSString *notabledata = [NSString stringWithFormat:@"No Dates Set"];
    [maincelltext addObject:notabledata];

}

return cell;
} 

谢谢!

2 个答案:

答案 0 :(得分:1)

你需要告诉UITableView需要插入行。首先确定新对象现在所在的数组中的索引,然后告诉UITableView插入这样的行:

NSIndexPath *indexPathOfNewObject=[NSIndexPath indexPathForRow: newObjectIndex section:0];
NSArray *indexPathArray=[NSArray arrayWithObject: indexPathOfNewObject];

[self.tableView beginUpdates];
// Note that UITableViewRowAnimationAutomatic is for iOS5 only.
[self.tableView insertRowsAtIndexPaths: indexPathArray withRowAnimation:UITableViewRowAnimationAutomatic];
[self.tableView endUpdates];

通过使用此方法,您将在tableView上获得很酷的动画效果。

或者,您可以调用[self.tableView reloadData],它只会重新加载所有数据。

祝你好运!

答案 1 :(得分:1)

执行[myTableView reloadData];之后,只需执行[myArray addObject:myObject];即可。您应该没事。

相关问题