直截了当,然后:
第一个片段(AppDelegate):
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
//...code taken out...
[NSEvent addGlobalMonitorForEventsMatchingMask:NSKeyDownMask handler:^(NSEvent *incomingEvent) {
if ([incomingEvent type] == NSKeyDown) {
NSUInteger flags = [incomingEvent modifierFlags] & NSDeviceIndependentModifierFlagsMask;
if (flags==NSCommandKeyMask && ([incomingEvent keyCode] == 8)) {
[ClipboardUtilities logger:@"cmd+c recognized"];
[self determineAndAddToHistory];
}
}
}];
}
第二个片段(AppDelegate):
-(void) determineAndAddToHistory {
id clipDat = [ClipboardUtilities getClipboardDataNatively];
if ([clipDat isKindOfClass:[NSAttributedString class]])
NSLog(@"clipDat.string = %@",((NSAttributedString*)clipDat).string);
}
第三个片段(ClipboardUtilities类):
+(id) getClipboardDataNatively {
NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
NSArray *classArray = @[[NSAttributedString class], [NSImage class]];
NSDictionary *options = [NSDictionary dictionary];
NSArray *objectsToPaste = nil;
BOOL ok = [pasteboard canReadObjectForClasses:classArray options:options];
if (ok) {
objectsToPaste = [pasteboard readObjectsForClasses:classArray options:options];
}
NSLog(@"objectsToPaste count = %li",[objectsToPaste count]);
return [objectsToPaste objectAtIndex:0];
}
我注意到一些奇怪的行为,我将尝试用一个例子来解释:
输入
来自determineAndAddToHistory的输出
所以我注意到它因某种原因保留了第一项......然后每次都返回第二项。我已经尝试在getClipboardDataNatively方法中输出objectsToPaste数组,但仍然如此。有人可以让我知道我将如何解决这个问题,或者他们是如何解决的?
P.S。我的ClipboardUtilities类没有实现任何Delegates,或者从NSObject继承。
答案 0 :(得分:0)
嗯,我想,因为没有人喜欢长问题(我必须弄清楚如何缩短这个问题),我想出了什么。出于某种原因,我很快就得到了热键调用(实际调用键后剪贴板会更新)。结果,我只是有一个小延迟,我的模型现在正确更新:
NSTimer* briefDelay = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(determineAndAddToHistory) userInfo:nil repeats:NO];
[[NSRunLoop mainRunLoop] addTimer:briefDelay forMode:NSRunLoopCommonModes];
我不会手动使计时器失效,根据文档:
repeats
If YES, the timer will repeatedly reschedule itself until invalidated. If NO, the timer will be invalidated after it fires.