Get path for NSFileWrapper

你。 提交于 2019-12-10 02:36:51

问题


Given an NSFileWrapper object (for a file or directory), is there any way to get the full path for the location of the actual file on the disk?

[fileWrapper filename] only returns the file name, not the path, so it isn't what I'm looking for.


回答1:


No, there's no way to get the full path from NSFileWrapper.




回答2:


If you're using NSDocument you can get the path of regular-file file wrappers with a little hack.

First create a NSFileWrapper subclass and overload the regular-file methods that receive a URL to store a copy of it.

@implementation RMFileWrapper

- (id) initWithURL:(NSURL *)url options:(NSFileWrapperReadingOptions)options error:(NSError *__autoreleasing *)outError {
    if (self = [super initWithURL:url options:options error:outError]) {
        self.originalURL = url;
    }
    return self;
}

- (BOOL) readFromURL:(NSURL *)url options:(NSFileWrapperReadingOptions)options error:(NSError *__autoreleasing *)outError {
    BOOL successful = [super readFromURL:url options:options error:outError];
    if (successful) {
        self.originalURL = url;
    }
    return successful;
}

@end

Then add this NSFileWrapper category:

@implementation NSFileWrapper(bestURLWithDocument)

- (NSURL*) bestURLInDocument:(SBDocument*)document {
    if (document.fileURL && self.filename) {
        NSString* path = [document.fileURL.path stringByAppendingPathComponent:self.filename];
        return [NSURL fileURLWithPath:path];
    } else if ([self isKindOfClass:[RMFileWrapper class]]) {
        RMFileWrapper *fileWrapper = (RMFileWrapper*) self;
        return fileWrapper.originalURL;        
    }
    return nil;
}

@end

bestURLInDocument: will return the url of the file-system node if available, or the original file url if not.

The above code assumes that you're not nesting directory file wrappers.



来源:https://stackoverflow.com/questions/8846193/get-path-for-nsfilewrapper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!