我有一个有会议的文件。当我初始化会议时,我将 undoManager 设置为指向 Document 的 undoManager。同样,我的会议有与会者(人员列表)。每个 Person 对象都简单地指向我会议的 undoManager,而后者又只是指向 Document 的指针。
在我开始观察人员属性的关键值之前,我在会议中添加和删除与会者的撤消操作一直有效。
关于我做错了什么的任何想法?当我添加和删除与会者时,撤消按钮未激活。同样,当我更改此人的姓名/费率时,撤消按钮不会出现。
文档.m
- (id)init
{
self = [super init];
if (self) {
self.meeting = [[Meeting alloc] init];
self.meeting.undoManager = self.undoManager;
会议.h ---
@property (nonatomic, retain) NSUndoManager *undoManager;
会议.m
- (void)changeKeyPath:(NSString *)keyPath
ofObject:(id)obj
toValue:(id)newValue {
// setValue:forKeyPath: will cause the key-value observing method
// to be called, which takes care of the undo stuff
[obj setValue:newValue forKeyPath:keyPath];
}
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
id oldValue = [change objectForKey:NSKeyValueChangeOldKey];
// NSNull objects are used to represent nil in a dictionary
if (oldValue == [NSNull null]) {
oldValue = nil;
}
[[self.undoManager prepareWithInvocationTarget:self] changeKeyPath:keyPath
ofObject:object
toValue:oldValue];
// Notify the undoManager
self.undoManager.actionName = @"Edit";
}
- (void)startObservingPerson:(Person *)person {
// TODO: Understand if I need something for context
[person addObserver:self
forKeyPath:@"name"
options:NSKeyValueObservingOptionOld
context:nil];
[person addObserver:self
forKeyPath:@"rate"
options:NSKeyValueObservingOptionOld
context:nil];
}
- (void)stopObservingPerson:(Person *)person {
[person removeObserver:self forKeyPath:@"name"];
[person removeObserver:self forKeyPath:@"rate"];
}
-(void) insertObject:(id *)object inAttendeeListAtIndex:(NSUInteger)index {
[(Person *)object setMeeting:self];
// Enable undo capabilities for edits to the name/rate
[self startObservingPerson:(Person *)object];
// insert the object / person
[self.attendeeList insertObject:(Person *)object atIndex:index];
//
// configure the undo for the insert
[[self.undoManager prepareWithInvocationTarget:self] removeObjectFromAttendeeListAtIndex:(NSUInteger) index];
undoManager.actionName = @"Insert Person";
}
-(void) removeObjectFromAttendeeListAtIndex:(NSUInteger)index {
Person *deletedPerson = [self.attendeeList objectAtIndex:index];
// housecleaning before removing the person
[self stopObservingPerson:(Person *)deletedPerson];
// remove the object / person
[self.attendeeList removeObjectAtIndex:index];
// configure the undo
[[self.undoManager prepareWithInvocationTarget:self] insertObject:(id *)deletedPerson inAttendeeListAtIndex:index];
// Notify the undoManager
undoManager.actionName = @"Remove Person";
}