Key-Value Coding(KVC),Key-Value Observing(KVO)和Cocoa Bindings for MonoMac

时间:2022-04-23
本文章向大家介绍Key-Value Coding(KVC),Key-Value Observing(KVO)和Cocoa Bindings for MonoMac,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Key-Value Coding(KVC)机制允许通过变量名设置(set)以及获取(get)变量值。变量名只是一个字符串,但通常我们称之为Key。KVC也就是Cocoa访问NSObjects的属性的方式而不用直接访问对象的属性。

比如说你有个对象叫做Movie,有三个属性:Title,Producer,Year。

using System;
using System.Collections.Generic;

namespace KVC
{

    public partial class Movie
    {
        public Movie () {}

        public string Title { get; set; }

        public string Producer { get; set; }

        public int Year { get; set; }

    }
}

可以直接通过对象Movie的属性访问到:

Movie movie = new Movie();
movie.Title = "Shrek - Forever After";  // to assign the value
var title = movie.Title;  // to read the property value

使用KVC可以直接通过NSObject的方法访问到属性的字符串值:

  • 设置属性的值SetValueForKey (NSObject value, NSString key)
  • 读取属性的值ValueForKey(NSString key)
Movie movie = new Movie();
movie.SetValueForKey((NSString)"Shrek - Forever After",(NSString)"Title");;  // to assign the value
var title = movie.ValueForKey((NSString)"Title");  // to read the property 

这非常类似于.NET的反射机制

Movie movie = new Movie();

Type sourceType =movie.GetType();
PropertyInfo info = sourceType.GetProperty("Title");

info.SetValue(movie, "Shrek - Forever After" , null);  // to assign the value
var title = info.GetValue(this,null));  // to read the property value 

只是.NET的反射代码显得有点长河丑陋,使用MonoMac的Cocoa将非常的优雅。

.NET类需要满足Key-Value Coding 编码规范,通过使用[Export("xxxxx")]进行装饰,xxxx就是Cocoa的Key了:

using System;
using System.Collections.Generic;

using MonoMac.Foundation;

namespace KVC
{

    public partial class Movie : NSObject
    {
        public Movie () {}

        [Export("title")]
        public string Title { get; set; }

        [Export("producer")]
        public string Producer { get; set; }

        [Export("year")]
        public int Year { get; set; }

    }
}

上面引入了MonoMac.Foundation命名空间,Movie类从NSObject类继承过来,三个属性使用Export属性修饰,这样Movie就可以满足Cocoa的KVC机制。

具体参考文章

http://cocoa-mono.org/archives/153/kvc-kvo-and-cocoa-bindings-oh-my-part-1/

http://tirania.org/monomac/archive/2010/Dec-07.html