Look,這是一個很簡單的要求,點擊Add me,age +1.
想一想的話很簡單的,設置一個屬性Nsinteger age,點擊button add me,直接加1在重新顯示Lable就好啦,不過,我們今天是來練習KVC和KVO的,蘋果的鍵值編程哈哈
首先我們定義一個Human的類,并且完成了它的初始化方法
#import <Foundation/Foundation.h>@interface human : NSObject@PRoperty (nonatomic,assign) NSString *name;@property (nonatomic,assign) NSInteger age;-(id)initHuman:(NSString *)Initname hisage:(NSInteger) Initage;@end
#import "human.h"@implementation human-(id)initHuman:(NSString *)Initname hisage:(NSInteger)Initage{ if(self=[super init]){ _name=Initname; _age=Initage; } return self;}@end
很普通很簡單。。。
下面在ViewControler中調用該類,完成對這個人的年齡的增加
#import <UIKit/UIKit.h>#import "human.h"@interface ViewController : UIViewController<UIWebViewDelegate>{ human *keith;}@property (weak, nonatomic) IBOutlet UILabel *Infoshow;- (IBAction)Addme:(id)sender;@end
#import "ViewController.h"@interface ViewController ()@end@implementation ViewController-(void)viewWillAppear:(BOOL)animated{ [super viewWillAppear:animated]; keith=[[human alloc]initHuman:@"keith" hisage:26]; self.Infoshow.text=[NSString stringWithFormat:@"name is %@,age is %ld",keith.name,keith.age]; [keith addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:nil];//}- (IBAction)Addme:(id)sender { keith.age+=1; }-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{ if ([keyPath isEqualToString:@"age"] && object==keith) { self.Infoshow.text=[NSString stringWithFormat:@"name is %@,age is %ld",keith.name,keith.age];//添加對keith keyPath的監視 }}-(void)dealloc{ [keith removeObserver:self forKeyPath:@"age"];//不用的時候移除注冊}@end
可以看出如果通過這樣的模式有個好處是能減少模型和視圖的耦合關鍵,模型只管運算,視圖的變化通過KVO監視鍵值的變化,自動更新。
|
新聞熱點
疑難解答