NSTextView如何禁用“您不拥有文件“ xxx”,也没有写权限。”

时间:2018-11-07 19:07:55

标签: nstextview nsdocument

我在基于文档的应用程序中有一个NSTextView。如果打开仅具有读取权限的文件并修改NSTextView的内容,则会收到一个对话框,指出:

  

您没有文件“ xxx”,也没有写权限。

但是此textview实际上并未与我打开的文档进行交互。是否有可能以某种方式取消NSTextView的这种行为?

1 个答案:

答案 0 :(得分:0)

我想出的代码如下:

#import <JRSwizzle/JRSwizzle.h>

@implementation NSDocument (Swizzle)

+ (void) load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSError * error = nil;

        SEL srcSelection = NSSelectorFromString(@"_checkAutosavingThenUpdateChangeCount:");
        SEL dstSelector = @selector(MyCheckAutosavingThenUpdateChangeCount:);

        [[NSDocument class] jr_swizzleMethod: srcSelection
                                      withMethod: dstSelector
                                           error: &error];
        NSLog(@"Error: %@", error);
    });
} // End of load

- (void) MyCheckAutosavingThenUpdateChangeCount: (unsigned long long) arg1
{
    // On updateChangeCount, we are going to catch if the firstresponder is our query window.
    // If the first responder is, then we will not mark a change. This is for two reasons:
    // 1. This is an sqlite app. Editing the query editor dosen't actually update our
    // document.
    // 2. If we do mark the document as updated and the query editor marks a change, we get
    // a popup stating that the document cant be updated, needs to be duplicated, yada, yada.
    NSWindow * keyWindow = [[NSApplication sharedApplication] keyWindow];
    if(NULL != keyWindow)
    {
        NSResponder * responder = keyWindow.firstResponder;
        // My code uses a NSTextView subclass. For copy/paste I'm just entering NSTextView.
        if([responder isKindOfClass: NSClassFromString(@"NSTextView")])
        {
            return;
        }
    }

    [self MyCheckAutosavingThenUpdateChangeCount: arg1];
} // End of MyCheckAutosavingThenUpdateChangeCount