当文档是 txt 文件时,保存文档的首选项
我想知道当文档只是一个简单的 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;
}
I wonder how can I save preferences of a document such as window size, position in the screen, etc when this document is just a simple txt file. (My app is a Text Editor)
I thought of NSUserDefaults and save file path but what would happen if file is moved later when the app is closed? Using NSUserDefaults is really a good idea?
I am looking for advice
Thanks
EDIT:
I added these two methods to MyDocument.m (Thanks to @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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能需要查看 setxattr 和 getxattr 来分别写入和读取文件的扩展属性。您可以在这些属性中添加您喜欢的任何内容。
setxattr手册页
You may want to take a look at setxattr and getxattr to write and read a file's extended attributes respectively. You can put pretty much whatever you like in these attributes.
setxattr man page