tableView操作数据持久化

self.navigationItem.rightBarButtonItem=self.editButtonItem;

    //创建文件管理器

    NSFileManager *fileManager=[NSFileManager defaultManager];

    //判断路径下是否存在文件

    if ([fileManager fileExistsAtPath:PATH])

    {

        self.Marr=[NSMutableArray arrayWithContentsOfFile:PATH];

        

    }

    else

        //给文件添加数据

    {

        [self.Marr addObject:@"aaa"];

        [self.Marr addObject:@"www"];

        [self.Marr addObject:@"zzz"];

    }

 

 

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell" forIndexPath:indexPath];

 

cell.textLabel.text=self.Marr[indexPath.row];

 return cell;

}

//删除tableView单元格的方法

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    //                      删除表视图单元格编辑界面风格

    if (editingStyle == UITableViewCellEditingStyleDelete)

    {

        //                         集合指定位置索引

        [self.Marr removeObjectAtIndex:indexPath.row];

//        q                 从数据源中删除行

        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];

    }

    //               插入表视图单元格编辑风格  标示图前面 +  -的风格

    else if (editingStyle == UITableViewCellEditingStyleInsert)

    {

        // 创建一个新的合适的类的实例,将其插入到数组,并添加一个新行表视图

        [self.Marr addObject:@"lamco"];

        

        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];

    }

    //数据持久化(激素hi把文件放到Directory文件中)

    [self.Marr writeToFile:PATH atomically:YES];

}

 

//移动tableView

// Override to support rearranging the table view.

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath

{

//    交互的四步

//    1、获取交互元素   赋给一个临时变量

//    2、从集合中删除交互位置的元素

//    3、叫临时字符串插入到指定位置

    NSString *tempstr=[self.Marr objectAtIndex:fromIndexPath.row];

    [self.Marr removeObject:tempstr];

    [self.Marr insertObject:tempstr atIndex:fromIndexPath.row];

    

    //数据持久化

    [self.Marr writeToFile:PATH atomically:YES];

}

 

posted @ 2016-03-28 21:01  火候  阅读(184)  评论(0编辑  收藏  举报