KVC KVO 鍵盤編碼 鍵值觀察

2021-07-08 13:32:57 字數 3121 閱讀 6691

方法列表

objc

// 獲取通過key

- (id)valueforkey:(nsstring *)key;

// 設定值

- (void)setvalue:(id)value forkey:(nsstring *)key;

- (id)valueforkeypath:(nsstring *)keypath;

- (void)setvalue:(id)value forkeypath:(nsstring *)keypath;

首先我們建立乙個類

objc

@inte***ce student : nsobjec

@property (nonatomic, strong) nsstring *name;

@property (nonatomic, strong) nsstring ****;

@property (nonatomic, strong) nsstring *code;

@property (nonatomic, assign) cgpoint position;

@end

按照我們以前的賦值方式,我們肯定會這樣做

objc

student *stu = [[student alloc] init];

// 進行賦值

stu.name = @"zhangsan";

stu.*** = @"male";

而如果使用kvc方式就可以使用以下**

objc

// 等價於

[stu setvalue:@"zhangsan" forkey:@"name"];

[stu setvalue:@"name" forkey:@"***"];

這兩種方式在這裡可以說是等價的,但是需要注意如果設定值對應的key不存在屬性列表中,那麼會存在崩潰現象,崩潰資訊如下:

reason: '[0x100206af0> setvalue:forundefinedkey:]: this class

isnot key value coding-compliant for

the key phone.'

所以,一定要注意key是存在屬性列表中才可以使用kvc

接著我們來看另外一種情況,如果這個學生擁有乙個老師,他想去設定老師對應的值,利用kvc應該怎麼實現呢

@inte***ce

teacher : nsobject

@property (nonatomic, assign) cgpoint position; // 位置

@property (nonatomic, strong) nsstring *name; // 姓名

@end

然後我們為學生新增乙個老師屬性

objc

@property (nonatomic, strong) teacher *teacher;

```

最後我們在main函式中

```objc

teacher *teacher = [[teacher alloc] init];

// 建立關聯

stu.teacher = teacher;

// 間接設定

stu.teacher.name = @"jone";

// 利用kvc,利用屬性名+點+相應的屬性名

[stu setvalue:@"mary" forkeypath:@"teacher.name"];

// 訪問

nslog(@"%@", stu.teacher.name);

```

有時我們需要監聽一些屬性的改變,然後執行相應的操作,現在我們來模擬乙個操作,比如學生發生老師的位置發生改變的時候,就進行相應的操作.

同樣我們在學生類中新增方法

```objc

#import "student.h"

@implementation student

- (void)watchteacherpositionchanged

其次直接在student.m檔案重寫該方法

``objc

// 當老師的位置發生改變時,自動呼叫該方法

- (void)observevalueforkeypath:(nsstring *)keypath ofobject:(id)object change:(nsdictionary *)change context:(void *)context

else

}}

然後在dealloc方法中

```objc

- (void)dealloc

最後在main函式中呼叫

```objc

student * stu1 = [[student alloc] init];

stu1.name = @"lisi"

; stu1.position = cgpointmake(1, 1);

student * stu2 = [[student alloc] init];

stu2.position = cgpointmake(4, 2);

stu2.name = @"zhangsan"

; // kvc kvo

teacher * teacher = [[teacher alloc] init];

stu1.teacher = teacher;

stu2.teacher = teacher;

// kvo

[stu1 watchteacherpositionchanged];

[stu2 watchteacherpositionchanged];

teacher.position = cgpointmake(1, 1);

teacher.position = cgpointmake(1, 2);

teacher.position = cgpointmake(4, 2);

鍵盤虛擬鍵值編碼表

模擬鍵盤輸入首先要用到乙個api函式 keybd event。我們是菜鳥,所以不必具體去理解它的詳細用法,只要按以下方法使用即可了!呵呵!模擬按鍵有兩個基本動作,即按下鍵和放開按鍵,所以我們每模擬一次按鍵就要呼叫兩次該api函式,其方法是 例子1 模擬按下 a 鍵 keybd event 65,0,...

鍵盤虛擬鍵值編碼表 使用keybd event

也是在cnblogs上找的,怕到時忘了,先記下來 原文章 http www.cnblogs.com nemolog archive 2005 10 30 265035.html 模擬鍵盤輸入首先要用到乙個api函式 keybd event。我們是菜鳥,所以不必具體去理解它的詳細用法,只要按以下方法使...

鍵盤虛擬鍵值編碼表 使用keybd Event

模擬鍵盤輸入首先要用到乙個api函式 keybd event。我們是菜鳥,所以不必具體去理解它的詳細用法,只要按以下方法使用即可了!呵呵!模擬按鍵有兩個基本動作,即按下鍵和放開按鍵,所以我們每模擬一次按鍵就要呼叫兩次該api函式,其方法是 例子1 模擬按下 a 鍵 keybd event 65,0,...