符合NSObject的类中-self方法的目的是什么? [英] What is the purpose of the -self method in NSObject-conformant classes?
问题描述
就是这样.为什么有人要(至少作为公共API)这样的方法?有实际用途吗?
That's it. Why would anyone want (at least as a public API) a method such as that? Is there any practical use for it?
推荐答案
self
方法对于键值编码(KVC)很有用.
The self
method is useful for Key-Value Coding (KVC).
使用KVC,您可以将对象视为字典.您可以使用包含属性名称的字符串访问对象的属性,如下所示:[view valueForKey:@"superview"]
.您可以使用包含关键路径的字符串沿属性链向下移动,如下所示:[view valueForKeyPath:@"superview.superview.center"]
.
With KVC, you can treat an object somewhat like a dictionary. You can access a property of the object using a string containing the name of the property, like this: [view valueForKey:@"superview"]
. You walk down a chain of properties using a string containing a key path, like this: [view valueForKeyPath:@"superview.superview.center"]
.
由于NSObject
具有self
方法,因此可以将self
用作键或键路径:[view valueForKey:@"self"]
.因此,如果您以编程方式构造密钥路径,或者从文件中读取密钥路径,则使用"self"
作为密钥可以避免编写特殊情况.
Since NSObject
has a self
method, you can use self
as the key or key path: [view valueForKey:@"self"]
. So if you're constructing your key paths programmatically, or reading them from a file, using "self"
as a key may allow you to avoid writing a special case.
您还可以在谓词中使用self
,如下所示:
You can also use self
in predicates, like this:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self beginswith \"foo\""];
NSArray *filteredArray = [arrayOfStrings filteredArrayWithPredicate:predicate];
在这种情况下,我不知道NSPredicate
是否实际上使用了self
方法(也许通过KVC).当然有可能.
I don't know whether NSPredicate
actually uses the self
method (perhaps via KVC) in this case. It's certainly possible.
这篇关于符合NSObject的类中-self方法的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!