zoukankan      html  css  js  c++  java
  • KVO与KVC的使用(转)

    转自http://www.cnblogs.com/mybkn/archive/2013/05/29/3104166.html

    KVO:

    在看KVO之前,有必要先了解下KVC,即,Key-Value Coding 键值对编程。通过key-value可以方便的存取数据。

    具体的操作简单说就是:setValue:forKey:   valueForKey:

    //book Object
    //.h
    #import <Foundation/Foundation.h>
    @class Author;
    @interface Book : NSObject{
        NSString *name;
        Author *author;
        float price;
        NSArray *relativeBooks;
    }
    @end
    #import "Book.h"
    @implementation Book
    @end
    Book *book = [[Book alloc] init];
        [book setValue:@"iOS book" forKey:@"name"];//这里要注意实例变量的名字不要写错,写错了不会有提示
        NSString *name = [book valueForKey:@"name"];
        NSLog(@">> %@",name);
        
        Author *author = [[Author alloc] init];
        [author setValue:@"Zhan" forKey:@"name"];
        [book setValue:author forKey:@"author"];
        
        NSString *authorName = [book valueForKeyPath:@"author.name"];
        NSLog(@">> %@",authorName);
        
        [book setValue:@"100" forKey:@"price"];
        NSLog(@">> %@",[book valueForKey:@"price"]);
        
        Book *book1 = [[Book alloc] init];
        [book1 setValue:@"4" forKey:@"price"];
        Book *book2 = [[Book alloc] init];
        [book2 setValue:@"6" forKey:@"price"];
        
        NSArray *books = [NSArray arrayWithObjects:book1,book2,nil];
        [book setValue:books forKey:@"relativeBooks"];
        NSLog(@">>%@",[book valueForKeyPath:@"relativeBooks.price"]);

    KVO是基于kvc实现的,采取的是观察者的模式:

        book4=[[Book alloc] init];
        //增加观察者,为本类,keypath为book中的price对象,所以为price
        [book4 addObserver:self forKeyPath:@"price" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:nil];
        //修改值
        [book4 setValue:@"4" forKey:@"price"];
    //回掉方法,只要book4的值一改变就会回调这个方法


    -(void) observeValueForKeyPath:(NSString *)keyPath
    ofObject:(id)object
    change:(NSDictionary *)change
    context:(void *)context{
    NSLog(@"cel back");
    if([keyPath isEqual:@"price"]){
    NSLog(@">>>>>>>price is changed");
    NSLog(@"old price is %@",[change objectForKey:@"old"]);
    NSLog(@"new price is %@",[change objectForKey:@"new"]);
    }
    }

  • 相关阅读:
    JS站点
    1011 World Cup Betting (20分)
    1007 Maximum Subsequence Sum (25分)(动态规划DP)
    1006 Sign In and Sign Out (25分)
    1005 Spell It Right (20分)
    1004 Counting Leaves (30分)(DFS)
    1003 Emergency (25分)(Dijkstra算法)
    1002 A+B for Polynomials (25分)
    1001 A+B Format (20分)
    canvas
  • 原文地址:https://www.cnblogs.com/xiaobaizhu/p/3373677.html
Copyright © 2011-2022 走看看