我想知道当文档只是一个简单的 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);
关于cocoa - 当文档是 txt 文件时,保存文档的首选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5630973/