KVC 使用哪种方法? [英] Which approach to use for KVC?

查看:62
本文介绍了KVC 使用哪种方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪种方式更适合用于键值编码?让我们假设 MyController 类有变量 myVariable.有人可以写出什么是好的意见,什么是坏的,为什么.

Which way is better to use for Key Value Coding? Lets assume that MyController class have variable myVariable. Could some one write opinion which is good which is bad and why.

// Method in the MyController class.
- (NSString*)myVariableKVC {
    return NSStringFromSelector(@selector(myVariable));
}

[myController addObserver:self
               forKeyPath:[myController myVariableKVC]
                  options:NSKeyValueObservingOptionNew
                  context:nil];

2.

[myController addObserver:self
               forKeyPath:@"myVariable"
                  options:NSKeyValueObservingOptionNew
                  context:nil];

在我看来,第一部分更好.我们没有硬编码的字符串,当我们使用 Refactor -> Rename... 进行重命名时,它将被重命名.

From my point of view first part is more better. We do not have hard coded strings and when we will do rename using Refactor -> Rename... then it will be renamed.

推荐答案

如果你有一个名为 -Wundeclared-selector 的警告(Xcode 名称:Undeclared Selector",Xcode 构建设置:GCC_WARN_UNDECLARED_SELECTOR) 启用,如果您更改选择器的名称(更改为未在任何地方声明为选择器的名称),第一种方法会从编译器给您一些警告,正如您指出的那样,这会略微减少-编码/魔术"字符串.不过,我不会为它有一个单独的方法,我只是这样做:

If you have a waring named -Wundeclared-selector (Xcode name: "Undeclared Selector", Xcode build setting: GCC_WARN_UNDECLARED_SELECTOR) enabled, the first way will give you some warning from the compiler if you change the name of the selector (to something that isn't declared anywhere as a selector) and as you point out, this marginally reduces hard-coded/"magic" strings. I wouldn't bother having a separate method for it though, I just do this:

[myController addObserver:self
               forKeyPath:NSStringFromSelector(@selector(myVariable))
                  options:NSKeyValueObservingOptionNew
                  context:nil];

默认情况下,在我查看的 Xcode 项目模板中,此警告开启,因此,如果您想要进行此检查,则需要为您的项目手动打开该警告.

This warning is not on by default in the Xcode project templates I looked at, so if you want this check, you'll need to manually turn on that warning for your project.

如果没有该警告,则没有区别,只是第一个方法会引发另一个函数调用(如果 ObjC 方法返回问题中出现的选择器,则会发送 ObjC 消息).我觉得这个警告曾经是默认开启的,但我想情况会发生变化.

Absent that warning, there's no difference, except that the first method incurs another function call (and ObjC message send in the case of having an ObjC method that returns the selector as appears in the question). I feel like this warning used to be on by default, but things change, I guess.

这篇关于KVC 使用哪种方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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