牛骨文教育服务平台(让学习变的简单)
博文笔记

iOS KVO观察数组

创建时间:2015-10-06 投稿人: 浏览次数:3228
//
//  RootTableViewController.m
//  KVO_观察数组 // //  Created by 王聪 on 14/8/13. //  Copyright (c) 2014年 Congwang. All rights reserved. //

#import "RootTableViewController.h"
#import "Stock.h"

@interface RootTableViewController ()
//数组属性
@property (nonatomic, strong)NSMutableArray *dataSource;
@end

@implementation RootTableViewController
- (void)dealloc{
    //移除观察者
    [self removeObserver:self forKeyPath:@"dataSource"context:NULL];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //数组初始化
    self.dataSource = [NSMutableArray array];
    //当前对象观察当前对象dataSource属性的变化
    [self addObserver:self forKeyPath:@"dataSource"options:NSKeyValueObservingOptionOld context:NULL];
    //
    UIBarButtonItem *right = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:selfaction:@selector(addSomething:)];
    self.navigationItem.rightBarButtonItem = right;
    //注册cell
    [self.tableView registerClass:[UITableViewCell class]forCellReuseIdentifier:@"cell"];
   
}
- (void)addSomething:(UIBarButtonItem *)sender{
    Stock *stock = [[Stock alloc] init];
    stock.stockName = @"中石化";
    int a = arc4random() % 1000 + 1;
    stock.price = a / 1.1;
    [self insertObject:stockinDataSourceAtIndex:self.dataSource.count];
   
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void*)context{
    if ([change[@"kind"] integerValue] == NSKeyValueChangeInsertion) {
        //插入单元格
        NSIndexPath *indexPath = [NSIndexPathindexPathForRow:self.dataSource.count - 1 inSection:0];
        //第一个参数, 插入单元格的indexPath
        // 二  : 插入时的动画
        [self.tableView insertRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationLeft];
    }else if ([change[@"kind"]integerValue] ==NSKeyValueChangeRemoval){
        NSIndexSet *set = change[@"indexes"];
        //枚举集合中的每一个值 (当前set中永远为一个)
        __block NSIndexPath *indexPath = nil;
        [set enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL*stop) {
            indexPath = [NSIndexPath indexPathForRow:idxinSection:0];
        }];
        //删除单元格
        [self.tableView deleteRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationFade];
    }else if ([change[@"kind"]integerValue] == NSKeyValueChangeReplacement){
        NSIndexSet *set = change[@"indexes"];
        //枚举集合中的每一个值 (当前set中永远为一个)
        __block NSIndexPath *indexPath = nil;
        [set enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL*stop) {
            indexPath = [NSIndexPath indexPathForRow:idxinSection:0];
        }];
        //更新单元格
        [self.tableView reloadRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationFade];
       
    }
}


//* 当我们观察 数组的变化时一定会要完成系统为我们生成的两个方法, 一个是insert, 一个是remove,必须配对出现, 在该方法中完成数组的对应操作


- (void)insertObject:(id)object inDataSourceAtIndex:(NSUInteger)index{
    //向数组中插入数据
    [self.dataSource insertObject:object atIndex:index];
}
//系统动态生成的方法
- (void)removeObjectFromDataSourceAtIndex:(NSUInteger)index{
    [self.dataSource removeObjectAtIndex:index];
}
//系统为我们生成了一个修改方法
- (void)replaceObjectInDataSourceAtIndex:(NSUInteger)index withObject:(id)object{
    //在该方法中修改数组的元素
    [self.dataSource replaceObjectAtIndex:indexwithObject:object];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    //取出模型
    Stock *stock = self.dataSource[indexPath.row];
    cell.textLabel.textColor = [UIColorcolorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0blue:arc4random()%256/255.0 alpha:1];
    cell.textLabel.text = [NSString stringWithFormat:@"%@ -- %f", stock.stockName, stock.price];
   
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //点击cell的时候修改对应cell的内容
    //1.先修改数据源
    //先找到模型
    Stock *stock = self.dataSource[indexPath.row];
    stock.stockName = @"中石油";
    [self replaceObjectInDataSourceAtIndex:indexPath.rowwithObject:stock];
}


// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    //删除
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //删除数据源
        [self removeObjectFromDataSourceAtIndex:indexPath.row];
       
    }//插入
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
       
    }
}


@end
Stock.h //
//  Stock.h
//  KVC_观察数组 // //  Created by 王聪 on 14/8/13. //  Copyright (c) 2014年 Congwang. All rights reserved. //

#import 

@interface Stock : NSObject
//股票的名字
@property (nonatomic, copy)NSString *stockName;
@property (nonatomic, assign)float price;//股票的价格
@end
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。