我在我的收藏中添加了一个观察者,并观察它的计数
[[[JHTaskSave defaults] tasks] addObserver:self forKeyPath:@"count" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
JHTaskSave 是一个单例对象,而 tasks 是一个 JHTaskCollection KVC 兼容,当我将一个对象添加到我的集合时:
[[[JHTaskSave defaults] tasks] addTask:newTask]
任务数发生变化但没有调用observeValueForKeyPath,我不明白为什么
这是我的收藏类:
@interface JHTaskCollection : NSObject <NSFastEnumeration>
{
NSMutableArray *_tasks;
}
@property (nonatomic) NSUInteger count;
- (id)taskAtIndex:(NSUInteger)index;
- (void)addTask:(JHTask *)task;
- (void)removeTask:(JHTask *)task;
- (void)insertObject:(id)key inTasksAtIndex:(NSUInteger)index;
- (void)removeObjectFromTasksAtIndex:(NSUInteger)index;
- (void)removeTaskAtIndexes:(NSIndexSet *)indexes;
- (NSArray *)taskAtIndexes:(NSIndexSet *)indexes;
@end
@implementation JHTaskCollection
- (id)init
{
if(self = [super init]) {
_tasks = [[NSMutableArray alloc] init];
}
return self;
}
- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id __unsafe_unretained *)stackbuf count:(NSUInteger)len
{
return [_tasks countByEnumeratingWithState:state objects:stackbuf count:len];
}
- (NSArray *)taskAtIndexes:(NSIndexSet *)indexes
{
return [_tasks objectsAtIndexes:indexes];
}
- (void)insertObject:(id)key inTasksAtIndex:(NSUInteger)index
{
[_tasks insertObject:key atIndex:index];
}
- (void)removeObjectFromTasksAtIndex:(NSUInteger)index
{
[_tasks removeObjectAtIndex:index];
}
- (void)removeTaskAtIndexes:(NSIndexSet *)indexes
{
[_tasks removeObjectsAtIndexes:indexes];
}
- (JHTask *)taskAtIndex:(NSUInteger)index
{
return [_tasks objectAtIndex:index];
}
- (NSUInteger)count
{
return _tasks.count;
}
- (void)addTask:(JHTask *)task
{
[_tasks addObject:task];
}
- (void)removeTask:(JHTask *)task
{
[_tasks removeObject:task];
}
@end