我试图更好地理解 Cocoa 的键值编码 (KVC) 机制。我已经阅读了 Apple 的Key-Value Programming Guide,但对于某些 KVC 方法如何搜索键仍然有些困惑。特别是mutableArrayValueForKey:。
下面我将解释我如何理解valueForKey:
KVC “getter”的工作原理。然后我会回答关于 mutableArrayValueForKey 的问题。
有七种不同的“getter”KVC 方法:
- (id)valueForKey:(NSString *)key;
- (id)valueForKeyPath:(NSString *)keyPath;
- (NSDictionary *)dictionaryWithValuesForKeys:(NSArray *)keys;
- (NSMutableArray *)mutableArrayValueForKey:(NSString *)key;
- (NSMutableArray *)mutableArrayValueForKeyPath:(NSString *)keyPath;
- (NSMutableSet *)mutableSetValueForKey:(NSString *)key;
- (NSMutableSet *)mutableSetValueForKeyPath:(NSString *)keyPath;
在属性(名为myKey)中搜索值时,Apple 的文档声明valueForKey:搜索如下:
- 在接收器内部尝试
-getMyKey
、-myKey
和-isMyKey
(按顺序) 如果没有找到,它会尝试这些有序的、对多的 getter(NSArray):
// Required: - (NSUInteger)countOfMyKey; // Requires At Least One: - (id)objectInMyKeyAtIndex:(NSUInteger)index; - (NSArray *)myKeyAtIndexes:(NSIndexSet *)indexes; // Optional (improves performance): - (void)getMyKey:(KeyClass **)buffer range:(NSRange)inRange;
接下来,它会尝试这些无序的、对多的 getter(NSSet):
- (NSUInteger)countOfMyKey; - (NSEnumerator *)enumeratorOfMyKey; - (KeyClass *)memberOfMyKey:(KeyClass *)anObject;
接下来,它尝试直接访问实例变量,假设
YES
由accessInstanceVariablesDirectly
,按以下顺序返回:_myKey
、_isMyKey
、myKey
、isMyKey
。最后,它放弃并调用接收类的
- (id)valueForUndefinedKey:(NSString *)key
方法。通常这里会引发错误。
我的问题是,mutableArrayValueForKey: 的搜索顺序模式是什么?
有序集合的访问者搜索模式
mutableArrayValueForKey: 的默认搜索模式如下:
在接收者的类中搜索名称匹配模式 -insertObject:inAtIndex: 和 -removeObjectFromAtIndex: 的一对方法(分别对应于 NSMutableArray 原始方法 insertObject:atIndex: 和 removeObjectAtIndex:),或匹配模式 -insert:atIndexes 的方法: 和 -removeAtIndexes: (对应于 NSMutableArrayinsertObjects:atIndexes: 和 removeObjectsAtIndexes: 方法)。如果找到至少一种插入方法和至少一种删除方法,则发送到集合代理对象的每个 NSMutableArray 消息将导致 -insertObject:inAtIndex:、-removeObjectFromAtIndex:、-insert:atIndexes: 和 -removeAtIndexes: 消息的某种组合被发送到 mutableArrayValueForKey: 的原始接收者。...ETC...
这对我来说毫无意义,因为它正在讨论类似“setter”的方法。 mutableArrayValueForKey:
返回一个 NSMutableArray。上面列出的所有方法都返回 void,并用于编辑 NSMutableArray,而不是获取它。例子:
- (void)insertMyKey:(KeyClass *)keyObject inMyKeyAtIndex:(NSUInteger)index;
- (void)removeObjectFromMyKeyAtIndex:(NSUInteger)index;
知道 Apple 在他们的文档中试图说什么,或者这可能是一个错误吗?
我的理论是,这可能会采用与搜索检索 KVC 值时mutableArrayValueForKey:
类似的路径。valueForKey:
我只是不确定那真的是什么路径。
谢谢你尽你所能的帮助!:)