关于tableview动态添加一行新数据

    UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(insertNewObject:)];

    self.navigationItem.rightBarButtonItem = addButton;


- (void)insertNewObject:(id)sender

{

    if (!_objects) {

        _objects = [[NSMutableArray alloc] init];

    }

    [_objects insertObject:[NSDate date] atIndex:0];

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];

    [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];

}

以上是MasterViewController自动生成的源代码

但在实际操作中自己碰到过一些问题

粘贴主要代码,解释原因

    [OrderModel GetItemsWithBlock:^(NSMutableArray *items,NSError *error)

     {

         if (error) {

             [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Error", nil) message:[error localizedDescription] delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"OK", nil), nil] show];

         } else {

             _items = items;

             _tempitems = items;

             [ordertableView reloadData];

         };

     } forStoreId:19311 withStatus:status  withOrderID:0];

此函数请求数据

- (void)insertNewObject:(id)sender

{

    if (!_items) {

        _items = [[NSMutableArray alloc] init];

    }

    if (_tempitems.count) {

        NSLog(@"%i",_tempitems.count);

    }

    NSLog(@"object0=%@",[_tempitems objectAtIndex:0]);

    [_items insertObject:[_tempitems objectAtIndex:0] atIndex:0];

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];

    [ordertableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];

}

此函数动态添加一行,运行时会到红色部分崩溃,为什么呢

原因是_items和_tempitems都是NSArray,但是申明变量的时候

@property NSMutableArray *items;

@property NSMutableArray *tempitems;

原来在model层传值的时候

    [[AFAppDotNetAPIClient sharedClient]getPath:@"orders/list" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {

        id items = [responseObject objectForKey:@"orders"];

        NSMutableArray *mutablePosts = [NSMutableArray arrayWithCapacity:[items count]];

        for (NSDictionary *attributes in items) {

            OrderModel *post = [[OrderModel alloc] initWithAttributes:attributes];

            [mutablePosts addObject:post];

        }

        

        if (block) {

            block([NSArray arrayWithArray:mutablePosts], nil);

        }

解决办法,讲NSArray换成NSMutableArray,问题解决

NSArray没有insertObject:atIndex 

这个方法只有NSMutableArray才有,它是可变数组,才能动态添加


你可能感兴趣的:(关于tableview动态添加一行新数据)