前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Key-Value Coding(KVC),Key-Value Observing(KVO)和Cocoa Bindings for MonoMac

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

作者头像
张善友
发布2018-01-19 16:38:19
9220
发布2018-01-19 16:38:19
举报
文章被收录于专栏:张善友的专栏张善友的专栏

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

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

代码语言:js
复制
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的属性访问到:

代码语言:js
复制
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)
代码语言:js
复制
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的反射机制

代码语言:js
复制
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了:

代码语言:js
复制
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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2011-02-03 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档