iOS KVO观察数组

本博客介绍了一个基于Objective-C实现的股票管理系统,详细阐述了如何通过数组操作实现股票数据的实时更新、添加、删除及修改。系统还包含了自定义的观察者机制来监控数组变化,并通过注册cell与表格视图的交互来展示数据。同时,展示了如何在用户操作下动态调整数组内容,并通过特定的按钮触发新增股票信息的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


#import 

@interface Stock : NSObject
//股票的名字
@property (nonatomic, copy)NSString *stockName;
@property (nonatomic, assign)float price;//股票的价格
@end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值