[__NSCFArray removeObjectAtIndex:]:发送到不可变对象的变异方法'

时间:2016-06-04 08:45:42

标签: ios objective-c uitableview

Hii我是ios developer的新手。我想删除tableview.i中的行将实现代码但是当我滑动tableview时,单击“删除”按钮而不是显示错误

[__ NSCFArray removeObjectAtIndex:]:发送到不可变对象的变异方法'

这是我的截图

enter image description here

这是我的代码

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
{
    return [cart_data count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    static NSString *simpleTableIdentifier = @"cellitem";

    cell *cells = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

    if (cells == nil) {
        cells = [[cell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }


    cells.lbl_title.text = [NSString stringWithFormat:@"%@",cart_data[indexPath.row][@"name"]];
    cells.lbl_price.text = [NSString stringWithFormat:@"%@",cart_data[indexPath.row][@"price"]];
    cells.lbl_qty.text = [NSString stringWithFormat:@"%@",cart_data[indexPath.row][@"qty"]];


    NSURL *url = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"%@",cart_data[indexPath.row][@"img_url"]]];

    [cells.image setImageWithURL:url placeholderImage:[UIImage imageNamed:@"imagename"] ];
    return cells;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return YES if you want the specified item to be editable.
    return YES;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {


        [cart_data removeObjectAtIndex:indexPath.row];

        [self.table deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath]
                         withRowAnimation:UITableViewRowAnimationFade];
        [self.table reloadData];
        //add code here for when you hit delete
    }
}

帮我解决任何问题......感谢您提前

1 个答案:

答案 0 :(得分:2)

错误消息明确指出cart_dataNSArray而不是预期的NSMutableArray

即使声明(和初始化)是正确的,也可能发生以后将不可变数组分配给该属性,使其不可变。在这种情况下,您需要在mutableCopy实例上调用NSArray

PS:您可以简化deleteRowsAtIndexPaths

...deleteRowsAtIndexPaths:@[indexPath] withRowAnimation...