• KVC的概述与使用


    KVC,即:Key-value coding,它是一种使用字符串标识符,间接访问对象属性的机制,它是很多技术的基础。

    主要的方法就两个,setValue:forKey,valueForKey

    Programming Guide中说,使用KVC可以简化代码,但事实上使用起来,还是要看具体情况。

    代码实例:

    1.首先定义两个DataModel,这种DataModel定义是无法访问属性的

    1. @interface BookData : NSObject {  
    2.     NSString * bookName;  
    3.     float price;  
    4.     AuthorData * author;  
    5. }  
    6. @end  
    7. @implementation BookData  
    8. @end 
    1. @interface AuthorData : NSObject {  
    2.     NSString * name;  
    3. }  
    4. @end  
    5. @implementation AuthorData  
    6. @end  

    2.使用KVC

    1. BookData * book1 = [[BookData alloc] init];  
    2. [book1 setValue:@"english" forKey:@"bookName"];  
    3. [book1 setValue:@"20.0" forKey:@"price"];  
    4. AuthorData * author1 = [[AuthorData alloc] init];  
    5. [author1 setValue:@"tom" forKey:@"name"];  
    6. [book1 setValue:author1 forKey:@"author"];  
    7.   
    8. NSLog(@"value=%@",[book1 valueForKey:@"bookName"]);  
    9. NSLog(@"price=%f",[[book1 valueForKey:@"price"] floatValue]);  
    10. NSLog(@"author=%@",[book1 valueForKeyPath:@"author.name"]);  
    11. [book1 release];  

    注意事项,在使用的时候,Key值不能写错,也就是属性的名字不能写错,大小写也是敏感的。

  • 相关阅读:
    优化-UITableView性能
    优化-预渲染加速iOS设备的图像显示
    UIWebView
    NSJSONSerialization
    UITableView UITableViewCell NSIndexPath
    NSDictionary NSMutableDictionary
    iOS Delegate NSNotificationCenter
    Php解决跨域名共享session方案整理专题
    memached共享session
    二级域名 session共享
  • 原文地址:https://www.cnblogs.com/swallow37/p/3623308.html
Copyright © 2020-2023  润新知