在 Cocoa 中观察多对多关系的键值对 [英] Key-Value-Observing a to-many relationship in Cocoa

查看:26
本文介绍了在 Cocoa 中观察多对多关系的键值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让键值观察适用于 NSMutableArray.下面是被观察类 MyObservee 的 .h 文件:

I am trying to get key-value-observing to work for an NSMutableArray. Below is the .h file for MyObservee, the observed class:

@interface MyObservee : NSObject {
    @private int someValue;
    @private NSMutableArray *someArray;
}

@property (readwrite,assign) int someValue;
- (NSMutableArray *)someArray;
@end

MyObserver 类实现了observeValueForKeyPath:ofObject:change:context:.这是我添加观察者的方法:

The class MyObserver implements observeValueForKeyPath:ofObject:change:context:. Here is how I add the observer:

MyObservee *moe = [[MyObservee alloc] init];
MyObserver *mobs = [[MyObserver alloc] init];

[moe addObserver:mobs 
      forKeyPath:@"someArray" 
         options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) 
         context:NULL];

[moe.someArray addObject:@"hi there"];

为什么 addObject: 消息不会作为对 someArray 键路径的更改触发?我觉得这里有一些我不完全理解的东西.

How come the addObject: message isn't triggering as a change to the someArray key path? I have a feeling there's something I don't fully understand here.

推荐答案

您需要实现 KVC 编程指南.然后您必须使用这些访问器来访问数组,KVO 触发将起作用.你也可以调用 -mutableArrayValueForKey: 并使用该数组来 addObject: 等等,它会依次调用访问器方法并且 KVO 触发也会发生.还有用于 NSSet 的 set 访问器,请参阅 这里这里.

You need to implement the indexed array accessors as defined in the KVC programming guide. Then you must use those accessors to access the array and the KVO triggering will work. You can also call -mutableArrayValueForKey: and use that array to addObject: and such and it will in turn call the accessor methods and the KVO triggering will occur as well. There are also set accessors for use in for NSSets, see here and here.

示例:

@interface MyClass : NSObject
{
    NSMutableArray *_orders;
}

@property(retain) NSMutableArray *orders;

- (NSUInteger)countOfOrders;
- (id)objectInOrdersAtIndex:(NSUInteger)index;
- (void)insertObject:(id)obj inOrdersAtIndex:(NSUInteger)index;
- (void)removeObjectFromOrdersAtIndex:(NSUInteger)index;
- (void)replaceObjectInOrdersAtIndex:(NSUInteger)index withObject:(id)obj;


@end

这篇关于在 Cocoa 中观察多对多关系的键值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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