cocoa - 当文档是 txt 文件时,保存文档的首选项

标签 cocoa macos

我想知道当文档只是一个简单的 txt 文件时,如何保存文档的首选项,例如窗口大小、屏幕位置等。 (我的应用程序是文本编辑器)

我想到了 NSUserDefaults 和保存文件路径,但是如果稍后在应用程序关闭时移动文件会发生什么?使用 NSUserDefaults 真的是个好主意吗? 我正在寻求建议

谢谢

编辑: 我将这两个方法添加到MyDocument.m中(感谢@somegeekintn @Black Frog)

//helper method that set NSWindow frame string in file system attributes
- (BOOL) _savePreferencesInFileAtURL:(NSURL *)absoluteURL{

    const char *path = [[absoluteURL path] fileSystemRepresentation];
    const char *name = [@"NSWindow frame" cStringUsingEncoding:NSUTF8StringEncoding];
    const char *frameCString = [NSStringFromRect([window frame]) cStringUsingEncoding:NSUTF8StringEncoding];

    int result = setxattr(path , name, frameCString, strlen(frameCString) + 1, 0, 0);
    return (result<0)? NO: YES;
}

//helper method that reads NSWindow frame string from file system attributes
- (BOOL) _readPreferencesInFileAtURL:(NSURL *)absoluteURL{

    const char *path = [[absoluteURL path] fileSystemRepresentation];
    const char *name = [@"NSWindow frame" cStringUsingEncoding:NSUTF8StringEncoding];
    char frameCString [50];

    ssize_t bytesRetrieved = getxattr(path, name, frameCString, 50, 0, 0); 
    //use frameCString...

    return (bytesRetrieved<0)? NO: YES; 
}

最佳答案

您可能需要查看 setxattr 和 getxattr 来分别写入和读取文件的扩展属性。您可以在这些属性中添加您喜欢的任何内容。

int setxattr(const char *path, const char *name, void *value, size_t size, u_int32_t position, int options);
ssize_t getxattr(const char *path, const char *name, void *value, size_t size, u_int32_t position, int options);

setxattr man page

关于cocoa - 当文档是 txt 文件时,保存文档的首选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5630973/

相关文章:

objective-c - 使用助手发布的 NSUserNotification 打开主应用程序

ios - 在 xcode 中打开方法下拉菜单的快捷方式

ios - 什么时候使用 NSSet 而不是 NSArray 更好?

objective-c - 监控沙盒应用程序中的文件夹

objective-c - 通过终端在 Cocoa 应用程序中进行语音

macos - 在 OS X 启动时运行 Python 脚本

c - 为什么 popen() 只工作一次?

找不到 MySQL 头文件 MySQL-python db

objective-c - 给定一个 webView,如何更改不同类文件中的 URL?

macos - NSSpeechSynthesizer 何时结束讲话?