iOS中的键值编码与访问器方法 [英] Key Value Coding vs accessor methods in iOS

查看:98
本文介绍了iOS中的键值编码与访问器方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解目标C中与KVC相关的某些理论部分.以下是我完成的示例.

I'm trying to understand some theory part in Objective C related to KVC. Following is the example I've done.

我正在使用Cookie类,它具有如下所示的属性

I'm having class call Cookie and it has a property like below

@property NSString *name;

接下来,我有另一个名为Person的类,它具有以下属性

Next, I have another class call Person and it has following property

@property Cookie *cookie;

Inside Person实施文件

Inside Person implementation file

#import "Cookie.h"

- (id)init
{
    self = [super init];
    if (self) {
        _cookie = [[Cookie alloc] init];
    }
    return self;
}

在ViewContrtoller中,我可以编写以下两个选项来获得相同的结果.

In my ViewContrtoller I can write following two options to get the same result.

使用KVC:

[me valueForKeyPath:@"cookie.name"]

使用访问器方法:

[[me cookie] name]

要编写访问器方法,我必须导入Cookie类,但在使用KVC时不需要.

To write accessor method , I had to import the Cookie class but doesn't need when using KVC.

除此之外,使用KVC或使用访问器方法有什么好处?是否存在任何性能问题或安全性问题或良好的编码习惯或任何其他好处?

Apart from that, what are the benefit of using KVC instead or using accessor methods? Is there any performance issue or security issue or good coding practice or any other benefit?

推荐答案

根据

尽管键值编码很有效,但是它增加了一个间接级别,该级别比直接方法调用要慢一些.仅当可以从键值编码中受益时,才应使用键值编码.

Though key-value coding is efficient, it adds a level of indirection that is slightly slower than direct method invocations. You should use key-value coding only when you can benefit from the flexibility that it provides.

但是我认为这可能有点过分谨慎.我怀疑除非您的应用程序对性能非常敏感,否则您是否需要过多担心.

But I think this is probably a little over-cautious; I doubt you need worry too much unless your app is very performance sensitive.

这篇关于iOS中的键值编码与访问器方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆