Showing posts with label NSFileWrapper example. Show all posts
Showing posts with label NSFileWrapper example. Show all posts

Sunday, June 16, 2013

NSFileWrapper NSFileWrapperWritingAtomic example in Objective C (iOS).


NSFileWrapper NSFileWrapperWritingAtomic

File Wrapper Writing Options
Writing options that can be set by the writeToURL:options:originalContentsURL:error: method.

enum {
NSFileWrapperWritingAtomic = 1 << 0,
NSFileWrapperWritingWithNameUpdating = 1 << 1
};
typedef NSUInteger NSFileWrapperWritingOptions;

Constants
NSFileWrapperWritingAtomic
Whether writing is done atomically.
You can use this option to ensure that, when overwriting a file package, the overwriting either completely succeeds or completely fails, with no possibility of leaving the file package in an inconsistent state. Because this option causes additional I/O, you shouldn't use it unnecessarily. For example, don't use this option in an override of -[NSDocument writeToURL:ofType:error:], because NSDocument safe-saving is already done atomically.
NSFileWrapperWritingWithNameUpdating
Whether descendant file wrappers are sent the setFilename: method if the writing succeeds.
This option is necessary when your application passes a URL in the originalContentsURL parameter to the writeToURL:options:originalContentsURL:error: method. Without using this option (and reusing child file wrappers properly), subsequent invocations of writeToURL:options:originalContentsURL:error: would not be able to reliably create hard links in a new file package, because the record of names in the old file package would be out of date.
NSFileWrapper NSFileWrapperWritingAtomic example.
- (BOOL)writeToURL:(NSURL *)absoluteURL ofType:(NSString *)typeName error:(NSError **)outError
{  
    NSFileWrapper *wrapper = [[NSFileWrapper alloc] initDirectoryWithFileWrappers:nil];
    [wrapper addRegularFileWithContents:[@"please work" dataUsingEncoding:NSUTF8StringEncoding] preferredFilename:@"foobar"];
    [wrapper writeToURL:absoluteURL options:NSFileWrapperWritingAtomic originalContentsURL:nil error:outError];

    NSDictionary *metadata = [NSDictionary dictionaryWithObject:@"0.1" forKey:@"Version"];
    NSURL *mdURL = [NSURL fileURLWithPath:[[absoluteURL path] stringByAppendingPathComponent:@"SiteInfo.plist"]];
    [metadata writeToURL:mdURL atomically:YES];

    return YES;
}

Example of [NSFileWrapper NSFileWrapperWritingAtomic].
NSFileManager *fileManager = [NSFileManager defaultManager];
NSFileWrapper *fw = [[NSFileWrapper alloc] initDirectoryWithFileWrappers:nil];
       
NSArray *subpaths = [fileManager subpathsAtPath:picsPath];
for (NSString *path in subpaths) {
   NSString *longPath = [picsPath stringByAppendingPathComponent:path];
   NSString *filename = [NSString stringWithFormat:@\"%@.jpg\", [[path componentsSeparatedByString:@\".\"] objectAtIndex:0]];
   NSData *pngData = [fileManager contentsAtPath:longPath];
   UIImage *pngImage = [UIImage imageWithData:pngData];
   NSData *jpgData = UIImageJPEGRepresentation(pngImage, 1.0f);
               
   [fw addRegularFileWithContents:jpgData preferredFilename:filename];
}
       
NSURL *destURL = [NSURL URLWithString:[NSString stringWithFormat:@\"file://%@\",[exportPath stringByAppendingPathComponent:@'Export']]];
       
[fw writeToURL:destURL options:NSFileWrapperWritingAtomic originalContentsURL:nil error:nil];

End of NSFileWrapper NSFileWrapperWritingAtomic example article.

NSFileWrapper writeToURL options originalContentsURL error example in Objective C (iOS).


NSFileWrapper writeToURL options originalContentsURL error

Recursively writes the entire contents of a file wrapper to a given file-system URL.

- (BOOL)writeToURL:(NSURL *)url options:(NSFileWrapperWritingOptions)options originalContentsURL:(NSURL *)originalContentsURL error:(NSError **)outError

Parameters of [NSFileWrapper writeToURL options originalContentsURL error]
url
URL of the file-system node to which the file wrapper’s contents are written.
options
Option flags for writing to the node located at url. See “File Wrapper Writing Options” for possible values.
originalContentsURL
The location of a previous revision of the contents being written. The default implementation of this method attempts to avoid unnecessary I/O by writing hard links to regular files instead of actually writing out their contents when the contents have not changed. The child file wrappers must return accurate values when sent the filename method for this to work. Use the NSFileWrapperWritingWithNameUpdating writing option to increase the likelihood of that.
Specify nil for this parameter if there is no earlier version of the contents or if you want to ensure that all the contents are written to files.
updateNames
YES to update the receiver’s filenames (its filename and—for directory file wrappers—the filenames of its sub–file wrappers) be changed to the filenames of the corresponding nodes in the file system, after a successful write operation. Use this in Save or Save As operations.
NO to specify that the receiver’s filenames not be updated. Use this in Save To operations.
outError
If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information.

Return Value of [NSFileWrapper writeToURL options originalContentsURL error]
YES when the write operation is successful. If not successful, returns NO after setting outError to an NSError object that describes the reason why the file wrapper’s contents could not be written.
NSFileWrapper writeToURL options originalContentsURL error example.
- (BOOL)writeToURL:(NSURL *)absoluteURL ofType:(NSString *)typeName error:(NSError **)outError
{  
    NSFileWrapper *wrapper = [[NSFileWrapper alloc] initDirectoryWithFileWrappers:nil];
    [wrapper addRegularFileWithContents:[@"please work" dataUsingEncoding:NSUTF8StringEncoding] preferredFilename:@"foobar"];
    [wrapper writeToURL:absoluteURL options:NSFileWrapperWritingAtomic originalContentsURL:nil error:outError];

    NSDictionary *metadata = [NSDictionary dictionaryWithObject:@"0.1" forKey:@"Version"];
    NSURL *mdURL = [NSURL fileURLWithPath:[[absoluteURL path] stringByAppendingPathComponent:@"SiteInfo.plist"]];
    [metadata writeToURL:mdURL atomically:YES];

    return YES;
}

Example of [NSFileWrapper writeToURL options originalContentsURL error].
NSFileManager *fileManager = [NSFileManager defaultManager];
NSFileWrapper *fw = [[NSFileWrapper alloc] initDirectoryWithFileWrappers:nil];
       
NSArray *subpaths = [fileManager subpathsAtPath:picsPath];
for (NSString *path in subpaths) {
   NSString *longPath = [picsPath stringByAppendingPathComponent:path];
   NSString *filename = [NSString stringWithFormat:@\"%@.jpg\", [[path componentsSeparatedByString:@\".\"] objectAtIndex:0]];
   NSData *pngData = [fileManager contentsAtPath:longPath];
   UIImage *pngImage = [UIImage imageWithData:pngData];
   NSData *jpgData = UIImageJPEGRepresentation(pngImage, 1.0f);
               
   [fw addRegularFileWithContents:jpgData preferredFilename:filename];
}
       
NSURL *destURL = [NSURL URLWithString:[NSString stringWithFormat:@\"file://%@\",[exportPath stringByAppendingPathComponent:@'Export']]];
       
[fw writeToURL:destURL options:NSFileWrapperWritingAtomic originalContentsURL:nil error:nil];

End of NSFileWrapper writeToURL options originalContentsURL error example article.

NSFileWrapper writeToURL example in Objective C (iOS).


NSFileWrapper writeToURL

Recursively writes the entire contents of a file wrapper to a given file-system URL.

- (BOOL)writeToURL:(NSURL *)url options:(NSFileWrapperWritingOptions)options originalContentsURL:(NSURL *)originalContentsURL error:(NSError **)outError

Parameters of [NSFileWrapper writeToURL]
url
URL of the file-system node to which the file wrapper’s contents are written.
options
Option flags for writing to the node located at url. See “File Wrapper Writing Options” for possible values.
originalContentsURL
The location of a previous revision of the contents being written. The default implementation of this method attempts to avoid unnecessary I/O by writing hard links to regular files instead of actually writing out their contents when the contents have not changed. The child file wrappers must return accurate values when sent the filename method for this to work. Use the NSFileWrapperWritingWithNameUpdating writing option to increase the likelihood of that.
Specify nil for this parameter if there is no earlier version of the contents or if you want to ensure that all the contents are written to files.
updateNames
YES to update the receiver’s filenames (its filename and—for directory file wrappers—the filenames of its sub–file wrappers) be changed to the filenames of the corresponding nodes in the file system, after a successful write operation. Use this in Save or Save As operations.
NO to specify that the receiver’s filenames not be updated. Use this in Save To operations.
outError
If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information.

Return Value of [NSFileWrapper writeToURL]
YES when the write operation is successful. If not successful, returns NO after setting outError to an NSError object that describes the reason why the file wrapper’s contents could not be written.
NSFileWrapper writeToURL example.
- (BOOL)writeToURL:(NSURL *)absoluteURL ofType:(NSString *)typeName error:(NSError **)outError
{  
    NSFileWrapper *wrapper = [[NSFileWrapper alloc] initDirectoryWithFileWrappers:nil];
    [wrapper addRegularFileWithContents:[@"please work" dataUsingEncoding:NSUTF8StringEncoding] preferredFilename:@"foobar"];
    [wrapper writeToURL:absoluteURL options:NSFileWrapperWritingAtomic originalContentsURL:nil error:outError];

    NSDictionary *metadata = [NSDictionary dictionaryWithObject:@"0.1" forKey:@"Version"];
    NSURL *mdURL = [NSURL fileURLWithPath:[[absoluteURL path] stringByAppendingPathComponent:@"SiteInfo.plist"]];
    [metadata writeToURL:mdURL atomically:YES];

    return YES;
}

Example of [NSFileWrapper writeToURL].
NSFileManager *fileManager = [NSFileManager defaultManager];
NSFileWrapper *fw = [[NSFileWrapper alloc] initDirectoryWithFileWrappers:nil];
       
NSArray *subpaths = [fileManager subpathsAtPath:picsPath];
for (NSString *path in subpaths) {
   NSString *longPath = [picsPath stringByAppendingPathComponent:path];
   NSString *filename = [NSString stringWithFormat:@\"%@.jpg\", [[path componentsSeparatedByString:@\".\"] objectAtIndex:0]];
   NSData *pngData = [fileManager contentsAtPath:longPath];
   UIImage *pngImage = [UIImage imageWithData:pngData];
   NSData *jpgData = UIImageJPEGRepresentation(pngImage, 1.0f);
               
   [fw addRegularFileWithContents:jpgData preferredFilename:filename];
}
       
NSURL *destURL = [NSURL URLWithString:[NSString stringWithFormat:@\"file://%@\",[exportPath stringByAppendingPathComponent:@'Export']]];
       
[fw writeToURL:destURL options:NSFileWrapperWritingAtomic originalContentsURL:nil error:nil];

End of NSFileWrapper writeToURL example article.

NSFileWrapper setPreferredFilename example in Objective C (iOS).


NSFileWrapper setPreferredFilename

Specifies the receiver’s preferred filename.

- (void)setPreferredFilename:(NSString *)filename

Parameters of [NSFileWrapper setPreferredFilename]
filename
Preferred filename for the receiver.

Discussion of [NSFileWrapper setPreferredFilename]
When a file wrapper is added to a parent directory file wrapper, the parent attempts to use the child’s preferred filename as the key in its dictionary of children. If that key is already in use, then the parent derives a unique filename from the preferred filename and uses that for the key.[NSFileWrapper setPreferredFilename]

When you change the preferred filename of a file wrapper, the default implementation of this method causes existing parent directory file wrappers to remove and re-add the child to accommodate the change. Preferred filenames of children are not preserved when you write a file wrapper to disk and then later instantiate another file wrapper by reading the file from disk. If you need to preserve the user-visible names of attachments, you have to store the names yourself.

Special Considerations
This method raises NSInvalidArgumentException if you pass nil or an empty value for filename.
NSFileWrapper setPreferredFilename example.
if (self.fileWrapper == nil) {
    self.fileWrapper = [[NSFileWrapper alloc] initDirectoryWithFileWrappers:nil];
}

NSDictionary *fileWrappers = [self.fileWrapper fileWrappers];

if (([fileWrappers objectForKey:@"page"] == nil) && (self.text != nil)) {
    NSData *textData = [self.text dataUsingEncoding:NSUTF8StringEncoding];
    NSFileWrapper *textFileWrapper = [[NSFileWrapper alloc] initRegularFileWithContents:textData];
    [textFileWrapper setPreferredFilename:@"page"];
    [self.fileWrapper addFileWrapper:textFileWrapper];
}

if (([fileWrappers objectForKey:@"pageSettings"] == nil) && (self.pageSettings != nil)) {
    NSData *settingsData = [NSKeyedArchiver archivedDataWithRootObject:self.pageSettings];
    NSFileWrapper *settingsWrapper = [[NSFileWrapper alloc] initRegularFileWithContents:settingsData];
    [settingsWrapper setPreferredFilename:@"pageSettings"];
    [self.fileWrapper addFileWrapper:settingsWrapper];
}

Example of [NSFileWrapper setPreferredFilename].
- (NSFileWrapper*)        fileWrapperOfType:(NSString*) typeName error:
(NSError**) outError
{
                NSData* mainContent = [self dataOfType:kDKDrawingDocumentType 
error:outError];

                if( mainContent == nil )
                {
                        *outError = [NSError errorWithDomain:kOrteliusErrorDomain 
code:kOrteliusNoDataErrorCode userInfo:nil];
                        return nil;
                }

                NSFileWrapper* fw = [[NSFileWrapper alloc] 
initDirectoryWithFileWrappers:nil];       
               
                [fw addRegularFileWithContents:mainContent 
preferredFilename:@"main_content"];
               
                // add "Quick Look" preview:
               
                NSFileWrapper* qlFolder = [[NSFileWrapper alloc] 
initDirectoryWithFileWrappers:nil];
                [qlFolder setPreferredFilename:@"QuickLook"];
                [fw addFileWrapper:qlFolder];
                [qlFolder release];
               
                // add preview and thumbnail
               
                NSData* preview = [[self drawing] thumbnailData];
                [qlFolder addRegularFileWithContents:preview 
preferredFilename:@"Thumbnail.jpg"];
               
                if( mSavePreview )
                {
                        preview = [[self drawing] pdf];
                        [qlFolder addRegularFileWithContents:preview 
preferredFilename:@"Preview.pdf"];
                }
               
                return [fw autorelease];

}

End of NSFileWrapper setPreferredFilename example article.

NSFileWrapper setFilename example in Objective C (iOS).


NSFileWrapper setFilename

Specifies the filename of a file wrapper.

- (void)setFilename:(NSString *)filename

Parameters of [NSFileWrapper setFilename]
filename
Filename of the file wrapper.

Discussion of [NSFileWrapper setFilename]
The file name is a dictionary key used to store fileWrapper in a directory’s list of child file wrappers. The dictionary key is a unique filename, which is the same as the child file wrapper's preferred filename unless that name is already in use as a key in the directory’s dictionary of children. See “Working With Directory Wrappers” in Application File Management for more information about the file-wrapper list structure. In general, the filename is set for you by the initWithURL:options:error:, initDirectoryWithFileWrappers:, or writeToURL:options:originalContentsURL:error: methods; you do not normally have to call this method directly.

Special Considerations
This method raises NSInvalidArgumentException if you pass nil or an empty value for filename.

NSFileWrapper setFilename example.
- (NSAttributedString *)pageFooter {                                                           
    NSString *imgName = @"Logo.tif";                                                           
    NSFileWrapper *fwrap = [[[NSFileWrapper alloc] initRegularFileWithContents:        
                 [[NSImage imageNamed:@"Logo"] TIFFRepresentation]] autorelease];
    [fwrap setFilename:imgName];
    [fwrap setPreferredFilename:imgName];

    NSTextAttachment * ta = [[[NSTextAttachment alloc] initWithFileWrapper:fwrap] autorelease];
    NSString *aString = @"Foo";
    NSMutableAttributedString *bString = [[NSMutableAttributedString alloc]initWithString:aString]];
    [bString appendAttributedString:[NSAttributedString attributedStringWithAttachment:ta]];
   [bString release];                                                                                 
    return bString;                                                                                    
}  

Example of [NSFileWrapper setFilename].
NSFileWrapper* filewrapper = [[NSFileWrapper alloc] init];
[filewrapper setFilename:filename];
NSTextAttachment* attachment = [[NSTextAttachment alloc] initWithFileWrapper:filewrapper]; 

NSFileWrapper setFilename example.
+(void)putIconForPath:(NSString*)path inTextView:(NSTextView*)textView {
    NSFileWrapper *filew = [[[NSFileWrapper alloc] initRegularFileWithContents:[NSData dataWithContentsOfFile:path]] autorelease];
    NSString* fileName = [path lastPathComponent];
    [filew setFilename:fileName];
    [filew setPreferredFilename:fileName];
   
    NSTextAttachment *fileAttatchment = [[[NSTextAttachment alloc] initWithFileWrapper:filew] autorelease];
    NSAttributedString *fileAttString = [NSAttributedString attributedStringWithAttachment:fileAttatchment];
   
    [textView insertText:fileAttString];
}

End of NSFileWrapper setFilename example article.

NSFileWrapper removeFileWrapper example in Objective C (iOS).


NSFileWrapper removeFileWrapper

Removes a child file wrapper from the receiver, which must be a directory file wrapper.

- (void)removeFileWrapper:(NSFileWrapper *)child

Parameters of [NSFileWrapper removeFileWrapper]
child
File wrapper to remove from the directory.
Special Considerations
This method raises NSInternalInconsistencyException if the receiver is not a directory file wrapper.

NSFileWrapper removeFileWrapper example.
NSFileWrapper *oldFileWrapper = [self.fileWrapper.fileWrappers objectForKey:fileName];
if (oldFileWrapper) [self.fileWrapper removeFileWrapper:oldFileWrapper];

[self.fileWrapper addRegularFileWithContents:[self encodeObject:object]
                           preferredFilename:fileName];

Example of [NSFileWrapper removeFileWrapper].
- (NSFileWrapper*) fileWrapperOfType:(NSString *)typeName error:(NSError *__autoreleasing *)outError {
    return self.documentFileWrapper;
}

- (BOOL) readFromFileWrapper:(NSFileWrapper *)fileWrapper ofType:(NSString *)typeName error:(NSError *__autoreleasing *)outError {
    self.documentFileWrapper = fileWrapper;
    return YES;
}

- (void) addFileToDocumentFromURL:(NSURL*)fileURL {
    NSData* fileData = [NSData dataWithContentsOfURL:fileURL];
    NSFileWrapper *fileWrapper = [[NSFileWrapper alloc] initRegularFileWithContents:fileData];
    fileWrapper.preferredFilename = [fileURL lastPathComponent];
    [self.documentFileWrapper addFileWrapper:fileWrapper];
    [self updateChangeCount:NSChangeDone];
}

- (void) removeFileFromDocumentWithName:(NSString*)name {
    NSFileWrapper *fileWrapper = [self.documentFileWrapper.fileWrappers objectForKey:name];
    if (fileWrapper) {
        [self.documentFileWrapper removeFileWrapper:fileWrapper];
        [self updateChangeCount:NSChangeDone];
    }
}

- (NSFileWrapper*) documentFileWrapper {
    if (!_documentFileWrapper) { // New document
        _documentFileWrapper = [[NSFileWrapper alloc] initDirectoryWithFileWrappers:nil];
    }
    return _documentFileWrapper;
}

NSFileWrapper removeFileWrapper example.
- (NSFileWrapper *)fileWrapperOfType:(NSString *)typeName
                               error:(NSError **)outError
{

    if ([self documentFileWrapper] == nil) {
        NSFileWrapper *documentFileWrapper = [[NSFileWrapper alloc] initDirectoryWithFileWrappers:nil];
        [self setDocumentFileWrapper:documentFileWrapper];
    }

    NSDictionary *fileWrappers = [documentFileWrapper fileWrappers];
    NSFileWrapper *textFileWrapper = [fileWrappers objectForKey:@"text.txt"];
    NSFileWrapper *videoFileWrapper = [fileWrappers objectForKey:@"video.mp4"];

    if ((textFileWrapper == nil && [self text] != nil) || [self textHasChanged]) {
        if (textFileWrapper != nil)
            [documentFileWrapper removeFileWrapper:textFileWrapper];

        if ([self text] != nil) {
            NSData *textData = [[self text] dataUsingEncoding:NSUTF8StringEncoding];
            [documentFileWrapper addRegularFileWithContents:textData preferredFileName:@"text.txt"];
        }
    }

    if ((videoFileWrapper == nil && [self videoData] != nil) || [self videoHasChanged]) {
        if (videoFileWrapper != nil)
            [documentFileWrapper removeFileWrapper:videoFileWrapper];

        if ([self videoData] != nil)
            [documentFileWrapper addRegularFileWithContents:[self videoData] preferredFileName:@"video.mp4"];
    }

    return documentFileWrapper;
}

End of NSFileWrapper removeFileWrapper example article.

NSFileWrapper regularFileContents example in Objective C (iOS).


NSFileWrapper regularFileContents

Returns the contents of the file-system node associated with a regular-file file wrapper.

- (NSData *)regularFileContents

Return Value
Contents of the file-system node the file wrapper represents.

Discussion of [NSFileWrapper regularFileContents]
This method may return nil if the user modifies the file after you call readFromURL:options:error: or initWithURL:options:error: but before NSFileWrapper has read the contents of the file. Use the NSFileWrapperReadingImmediate reading option to reduce the likelihood of that problem.

Special Considerations
This method raises NSInternalInconsistencyException if the receiver is not a regular-file file wrapper.

NSFileWrapper regularFileContents example.
NSDictionary *fileWrappers = [self.fileWrapper fileWrappers];
self.text = [[NSString alloc] initWithData:[[fileWrappers objectForKey:@"page"] regularFileContents] encoding: NSUTF8StringEncoding];
self.pageSettings = [NSKeyedUnarchiver unarchiveObjectWithData:[[fileWrappers objectForKey:@"pageSettings"] regularFileContents]];

Example of [NSFileWrapper regularFileContents].
- (BOOL)readFromURL:(NSURL *)url error:(NSError **)outError;
{   
    self.fileWrapper = [[NSFileWrapper alloc] initWithURL:url options:nil error:outError];
    NSString *rtfFilename = [url lastPathComponent];
    NSFileWrapper *rtfWrapper = [self.fileWrapper.fileWrappers objectForKey:rtfFilename];
    NSString *rtfString = [[NSString alloc] initWithData:[rtfWrapper regularFileContents] encoding:NSUTF8StringEncoding];
    NSAttributedString *attributedString = [OUIRTFReader parseRTFString:rtfString];
   
    _text = [attributedString copy];
   
    return YES;
}

NSFileWrapper regularFileContents example.
- (BOOL)loadFileWrapperRepresentation:(NSFileWrapper *)wrapper ofType:(NSString *)type
{
    if ([type isEqualToString:@"Rich-Text With Attachments"]) {
        rtfData = [[NSAttributedString alloc]initWithRTFDFileWrapper:wrapper documentAttributes:nil];
    } else if ([type isEqualToString:@"Rich-Text"]) {
        rtfData = [[NSAttributedString alloc]
            initWithRTF:[wrapper regularFileContents] documentAttributes:nil];
    } else if ([type isEqualToString:@"Plain-Text"]) {
        fileContents = [[NSString alloc]
                initWithData:[wrapper regularFileContents] encoding:nil];
        rtfData = [[NSAttributedString alloc]initWithString:fileContents];
    }

    if (textView) {                                                               
        [[textView textStorage]replaceCharactersInRange:NSMakeRange(0, [[textView string] length])withAttributedString:rtfData];
        [rtfData release];                                                        
     }
     return YES;
}

- (NSFileWrapper *)fileWrapperRepresentationOfType:(NSString *)type
{
    NSRange range = NSMakeRange(0, [[textView string] length]);
    if ([type isEqualToString:@"Rich-Text With Attachments"]) {
        return [[textView textStorage] RTFDFileWrapperFromRange:range documentAttributes:nil];
    } else if ([type isEqualToString:@"Rich-Text"]) {
        NSFileWrapper * wrapper = [[NSFileWrapper alloc]
            initRegularFileWithContents:[textView RTFFromRange:range]];
        return [wrapper autorelease];
    } else if ([type isEqualToString:@"Plain-Text"]) {
        //haven't implemented plain-text saving yet
     }
}

End of NSFileWrapper regularFileContents example article.

NSFileWrapper readFromURL options error example in Objective C (iOS).


NSFileWrapper readFromURL options error

Recursively rereads the entire contents of a file wrapper from the specified location on disk.

- (BOOL)readFromURL:(NSURL *)url options:(NSFileWrapperReadingOptions)options error:(NSError **)outError

Parameters of [NSFileWrapper readFromURL options error]
url
URL of the file-system node corresponding to the file wrapper.
options
Option flags for reading the node located at url. See “File Wrapper Reading Options” for possible values.
outError
If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information.

Return Value of [NSFileWrapper readFromURL options error]
YES if successful. If not successful, returns NO after setting outError to an NSError object that describes the reason why the file wrapper could not be reread.

Discussion of [NSFileWrapper readFromURL options error]
When reading a directory, children are added and removed as necessary to match the file system.

NSFileWrapper readFromURL options error example.
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

End of NSFileWrapper readFromURL options error example article.

NSFileWrapper readFromURL example in Objective C (iOS).


NSFileWrapper readFromURL

Recursively rereads the entire contents of a file wrapper from the specified location on disk.

- (BOOL)readFromURL:(NSURL *)url options:(NSFileWrapperReadingOptions)options error:(NSError **)outError

Parameters of [NSFileWrapper readFromURL]
url
URL of the file-system node corresponding to the file wrapper.
options
Option flags for reading the node located at url. See “File Wrapper Reading Options” for possible values.
outError
If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information.

Return Value of [NSFileWrapper readFromURL]
YES if successful. If not successful, returns NO after setting outError to an NSError object that describes the reason why the file wrapper could not be reread.

Discussion of [NSFileWrapper readFromURL]
When reading a directory, children are added and removed as necessary to match the file system.

NSFileWrapper readFromURL example.
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

End of NSFileWrapper readFromURL example article.

NSFileWrapper initWithURL options error example in Objective C (iOS).


NSFileWrapper initWithURL options error

Initializes a file wrapper instance whose kind is determined by the type of file-system node located by the URL.

- (id)initWithURL:(NSURL *)url options:(NSFileWrapperReadingOptions)options error:(NSError **)outError

Parameters of [NSFileWrapper initWithURL options error]
url
URL of the file-system node the file wrapper is to represent.
options
Option flags for reading the node located at url. See “File Wrapper Reading Options” for possible values.
outError
If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information.

Return Value of [NSFileWrapper initWithURL options error]
File wrapper for the file-system node at url. May be a directory, file, or symbolic link, depending on what is located at the URL. Returns NO (0) if reading is not successful.

Discussion of [NSFileWrapper initWithURL options error]
If url is a directory, this method recursively creates file wrappers for each node within that directory. Use the fileWrappers method to get the file wrappers of the nodes contained by the directory.

NSFileWrapper initWithURL options error example.
- (NSData *)exportToNSData {
    NSError *error;
    NSURL *url = [NSURL fileURLWithPath:_docPath];
    NSFileWrapper *dirWrapper = [[[NSFileWrapper alloc] initWithURL:url options:0 error:&error] autorelease];
    if (dirWrapper == nil) {
        NSLog(@"Error creating directory wrapper: %@", error.localizedDescription);
        return nil;
    }  

    NSData *dirData = [dirWrapper serializedRepresentation];
    NSData *gzData = [dirData gzipDeflate];   
    return gzData;
}

Example of [NSFileWrapper initWithURL options error].
NSError *error;
NSFileWrapper *fw = [[NSFileWrapper alloc] initWithURL:url options:0 error:&error];
// After the above method has been called, `error` is either `nil` (if all went well),
// or non-`nil` (if something went wrong).

NSFileWrapper initWithURL options error example.

- (BOOL)readFromURL:(NSURL *)url error:(NSError **)outError;
{
self.fileWrapper = [[NSFileWrapper alloc] initWithURL:url options:nil error:outError];
NSString *rtfFilename = [url lastPathComponent];
NSFileWrapper *rtfWrapper = [self.fileWrapper.fileWrappers objectForKey:rtfFilename];
NSString *rtfString = [[NSString alloc] initWithData:[rtfWrapper regularFileContents] encoding:NSUTF8StringEncoding];
NSAttributedString *attributedString = [OUIRTFReader parseRTFString:rtfString];

_text = [attributedString copy];

return YES;
}

End of NSFileWrapper initWithURL options error example article.

NSFileWrapper initWithURL example in Objective C (iOS).


NSFileWrapper initWithURL

Initializes a file wrapper instance whose kind is determined by the type of file-system node located by the URL.

- (id)initWithURL:(NSURL *)url options:(NSFileWrapperReadingOptions)options error:(NSError **)outError

Parameters of [NSFileWrapper initWithURL]
url
URL of the file-system node the file wrapper is to represent.
options
Option flags for reading the node located at url. See “File Wrapper Reading Options” for possible values.
outError
If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information.

Return Value of [NSFileWrapper initWithURL]
File wrapper for the file-system node at url. May be a directory, file, or symbolic link, depending on what is located at the URL. Returns NO (0) if reading is not successful.

Discussion of [NSFileWrapper initWithURL]
If url is a directory, this method recursively creates file wrappers for each node within that directory. Use the fileWrappers method to get the file wrappers of the nodes contained by the directory.

NSFileWrapper initWithURL example.
- (NSData *)exportToNSData {
    NSError *error;
    NSURL *url = [NSURL fileURLWithPath:_docPath];
    NSFileWrapper *dirWrapper = [[[NSFileWrapper alloc] initWithURL:url options:0 error:&error] autorelease];
    if (dirWrapper == nil) {
        NSLog(@"Error creating directory wrapper: %@", error.localizedDescription);
        return nil;
    }  

    NSData *dirData = [dirWrapper serializedRepresentation];
    NSData *gzData = [dirData gzipDeflate];   
    return gzData;
}

Example of [NSFileWrapper initWithURL].
NSError *error;
NSFileWrapper *fw = [[NSFileWrapper alloc] initWithURL:url options:0 error:&error];
// After the above method has been called, `error` is either `nil` (if all went well),
// or non-`nil` (if something went wrong).

NSFileWrapper initWithURL example.

- (BOOL)readFromURL:(NSURL *)url error:(NSError **)outError;
{
self.fileWrapper = [[NSFileWrapper alloc] initWithURL:url options:nil error:outError];
NSString *rtfFilename = [url lastPathComponent];
NSFileWrapper *rtfWrapper = [self.fileWrapper.fileWrappers objectForKey:rtfFilename];
NSString *rtfString = [[NSString alloc] initWithData:[rtfWrapper regularFileContents] encoding:NSUTF8StringEncoding];
NSAttributedString *attributedString = [OUIRTFReader parseRTFString:rtfString];

_text = [attributedString copy];

return YES;
}

End of NSFileWrapper initWithURL example article.

NSFileWrapper initRegularFileWithContents example in Objective C (iOS).


NSFileWrapper initRegularFileWithContents

Initializes the receiver as a regular-file file wrapper.

- (id)initRegularFileWithContents:(NSData *)contents

Parameters
contents
Contents of the file.

Return Value
Initialized regular-file file wrapper containing contents.

Discussion of [NSFileWrapper initRegularFileWithContents]
After initialization, the file wrapper is not associated with a file-system node until you save it using writeToURL:options:originalContentsURL:error:.

The file wrapper is initialized with open permissions: anyone can write to or read the file wrapper. .

NSFileWrapper initRegularFileWithContents example.
- (NSFileWrapper*) fileWrapperOfType:(NSString *)typeName error:(NSError *__autoreleasing *)outError {
    return self.documentFileWrapper;
}

- (BOOL) readFromFileWrapper:(NSFileWrapper *)fileWrapper ofType:(NSString *)typeName error:(NSError *__autoreleasing *)outError {
    self.documentFileWrapper = fileWrapper;
    return YES;
}

- (void) addFileToDocumentFromURL:(NSURL*)fileURL {
    NSData* fileData = [NSData dataWithContentsOfURL:fileURL];
    NSFileWrapper *fileWrapper = [[NSFileWrapper alloc] initRegularFileWithContents:fileData];
    fileWrapper.preferredFilename = [fileURL lastPathComponent];
    [self.documentFileWrapper addFileWrapper:fileWrapper];
    [self updateChangeCount:NSChangeDone];
}

- (void) removeFileFromDocumentWithName:(NSString*)name {
    NSFileWrapper *fileWrapper = [self.documentFileWrapper.fileWrappers objectForKey:name];
    if (fileWrapper) {
        [self.documentFileWrapper removeFileWrapper:fileWrapper];
        [self updateChangeCount:NSChangeDone];
    }
}

- (NSFileWrapper*) documentFileWrapper {
    if (!_documentFileWrapper) { // New document
        _documentFileWrapper = [[NSFileWrapper alloc] initDirectoryWithFileWrappers:nil];
    }
    return _documentFileWrapper;
}

Example of [NSFileWrapper initRegularFileWithContents].
- (void)encodeObject:(id<NSCoding>)object toWrappers:(NSMutableDictionary *)wrappers preferredFilename:(NSString *)preferredFilename {
    @autoreleasepool {
        NSMutableData * data = [NSMutableData data];
        NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
        [archiver encodeObject:object forKey:@"data"];
        [archiver finishEncoding];
        NSFileWrapper * wrapper = [[NSFileWrapper alloc] initRegularFileWithContents:data];
        [wrappers setObject:wrapper forKey:preferredFilename];
    }

NSFileWrapper initRegularFileWithContents example.
if (self.fileWrapper == nil) {
    self.fileWrapper = [[NSFileWrapper alloc] initDirectoryWithFileWrappers:nil];
}

NSDictionary *fileWrappers = [self.fileWrapper fileWrappers];

if (([fileWrappers objectForKey:@"page"] == nil) && (self.text != nil)) {
    NSData *textData = [self.text dataUsingEncoding:NSUTF8StringEncoding];
    NSFileWrapper *textFileWrapper = [[NSFileWrapper alloc] initRegularFileWithContents:textData];
    [textFileWrapper setPreferredFilename:@"page"];
    [self.fileWrapper addFileWrapper:textFileWrapper];
}

if (([fileWrappers objectForKey:@"pageSettings"] == nil) && (self.pageSettings != nil)) {
    NSData *settingsData = [NSKeyedArchiver archivedDataWithRootObject:self.pageSettings];
    NSFileWrapper *settingsWrapper = [[NSFileWrapper alloc] initRegularFileWithContents:settingsData];
    [settingsWrapper setPreferredFilename:@"pageSettings"];
    [self.fileWrapper addFileWrapper:settingsWrapper];
}

End of NSFileWrapper initRegularFileWithContents example article.

NSFileWrapper initDirectoryWithFileWrappers example in Objective C (iOS).


NSFileWrapper initDirectoryWithFileWrappers

Initializes the receiver as a directory file wrapper, with a given file-wrapper list.

- (id)initDirectoryWithFileWrappers:(NSDictionary *)childrenByPreferredName

Parameters
childrenByPreferredName
Key-value dictionary of file wrappers with which to initialize the receiver. The dictionary must contain entries whose values are the file wrappers that are to become children and whose keys are filenames. See “Working With Directory Wrappers” in Application File Management for more information about the file-wrapper list structure.

Return Value of [NSFileWrapper initDirectoryWithFileWrappers]
Initialized file wrapper for fileWrappers.

Discussion of [NSFileWrapper initDirectoryWithFileWrappers]
After initialization, the file wrapper is not associated with a file-system node until you save it using writeToURL:options:originalContentsURL:error:.

The receiver is initialized with open permissions: anyone can read, write, or modify the directory on disk.

If any file wrapper in the directory doesn’t have a preferred filename, its preferred name is automatically set to its corresponding key in the childrenByPreferredName dictionary.

NSFileWrapper initDirectoryWithFileWrappers example.
- (NSFileWrapper *)fileWrapperOfType:(NSString *)typeName
                               error:(NSError **)outError
{
    NSFileWrapper *dirWrapper = [[[NSFileWrapper alloc]
        initDirectoryWithFileWrappers:nil] autorelease];

    [dirWrapper addRegularFileWithContents:self.pdfData
        preferredFilename:@"MainDocument.pdf"];

    [dirWrapper addRegularFileWithContents:self.signatureBitmapData
        preferredFilename:@"SignatureBitmap.png"];

    …

    return dirWrapper;
}

Example of [NSFileWrapper initDirectoryWithFileWrappers].
- (NSFileWrapper *)fileWrapperOfType:(NSString *)typeName
                               error:(NSError **)outError;
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    NSFileWrapper * localizedWrapper =
    [[NSFileWrapper alloc] initDirectoryWithFileWrappers:localizedWrappers];
    [resourcesWrappers setObject:localizedWrapper
                          forKey:@"en.lproj"];
    NSFileWrapper * resourcesWrapper =
    [[NSFileWrapper alloc] initDirectoryWithFileWrappers:resourcesWrappers];
    [contentsWrappers setObject:resourcesWrapper
                         forKey:@"Resources"];
    NSFileWrapper * contentsWrapper =
    [[NSFileWrapper alloc] initDirectoryWithFileWrappers:contentsWrappers];
    // …
    for (id item in mumble) {
        NSString * filename = [item filename];
        NSData * data = [item data];
        [localizedWrapper addRegularFileWithContents:data
                                   preferredFilename:filename];
    }
    [contentsWrapper addRegularFileWithContents:[self infoPlistData]
                              preferredFilename:@"Info.plist"];
    [pool drain];
    [bundleWrappers setObject:contentsWrapper
                       forKey:@"Contents"];
    NSFileWrapper * bundleWrapper =
    [[[NSFileWrapper alloc] initDirectoryWithFileWrappers:bundleWrappers] autorelease];
    return bundleWrapper;
}

NSFileWrapper initDirectoryWithFileWrappers example.
if (self.fileWrapper == nil) {
    self.fileWrapper = [[NSFileWrapper alloc] initDirectoryWithFileWrappers:nil];
}

NSDictionary *fileWrappers = [self.fileWrapper fileWrappers];

if (([fileWrappers objectForKey:@"page"] == nil) && (self.text != nil)) {
    NSData *textData = [self.text dataUsingEncoding:NSUTF8StringEncoding];
    NSFileWrapper *textFileWrapper = [[NSFileWrapper alloc] initRegularFileWithContents:textData];
    [textFileWrapper setPreferredFilename:@"page"];
    [self.fileWrapper addFileWrapper:textFileWrapper];
}

if (([fileWrappers objectForKey:@"pageSettings"] == nil) && (self.pageSettings != nil)) {
    NSData *settingsData = [NSKeyedArchiver archivedDataWithRootObject:self.pageSettings];
    NSFileWrapper *settingsWrapper = [[NSFileWrapper alloc] initRegularFileWithContents:settingsData];
    [settingsWrapper setPreferredFilename:@"pageSettings"];
    [self.fileWrapper addFileWrapper:settingsWrapper];
}

End of NSFileWrapper initDirectoryWithFileWrappers example article.

NSFileWrapper fileWrappers example in Objective C (iOS).


NSFileWrapper fileWrappers

Returns the file wrappers contained by a directory file wrapper.

- (NSDictionary *)fileWrappers

Return Value of [NSFileWrapper fileWrappers]
A key-value dictionary of the file wrappers contained in the directory. The dictionary contains entries whose values are the file wrappers and whose keys are the unique filenames that have been assigned to each one. See “Working With Directory Wrappers” in Application File Management for more information about the file-wrapper list structure.

Discussion of [NSFileWrapper fileWrappers]
Returns a dictionary whose values are the file wrapper's children and whose keys are the unique filenames that have been assigned to each one. This method may return nil if the user modifies the directory after you call readFromURL:options:error: or initWithURL:options:error: but before NSFileWrapper has read the contents of the directory. Use the NSFileWrapperReadingImmediate reading option to reduce the likelihood of that problem.

Special Considerations
This method raises NSInternalInconsistencyException if the receiver is not a directory file wrapper.

NSFileWrapper fileWrappers example.
NSDictionary *fileWrappers = [self.fileWrapper fileWrappers];
self.text = [[NSString alloc] initWithData:[[fileWrappers objectForKey:@"page"] regularFileContents] encoding: NSUTF8StringEncoding];
self.pageSettings = [NSKeyedUnarchiver unarchiveObjectWithData:[[fileWrappers objectForKey:@"pageSettings"] regularFileContents]];

Example of [NSFileWrapper fileWrappers].
NSFileWrapper *oldFileWrapper = [self.fileWrapper.fileWrappers objectForKey:fileName];
if (oldFileWrapper) [self.fileWrapper removeFileWrapper:oldFileWrapper];

[self.fileWrapper addRegularFileWithContents:[self encodeObject:object]
                           preferredFilename:fileName];

NSFileWrapper fileWrappers example.
- (NSFileWrapper*) fileWrapperOfType:(NSString *)typeName error:(NSError *__autoreleasing *)outError {
    return self.documentFileWrapper;
}

- (BOOL) readFromFileWrapper:(NSFileWrapper *)fileWrapper ofType:(NSString *)typeName error:(NSError *__autoreleasing *)outError {
    self.documentFileWrapper = fileWrapper;
    return YES;
}

- (void) addFileToDocumentFromURL:(NSURL*)fileURL {
    NSData* fileData = [NSData dataWithContentsOfURL:fileURL];
    NSFileWrapper *fileWrapper = [[NSFileWrapper alloc] initRegularFileWithContents:fileData];
    fileWrapper.preferredFilename = [fileURL lastPathComponent];
    [self.documentFileWrapper addFileWrapper:fileWrapper];
    [self updateChangeCount:NSChangeDone];
}

- (void) removeFileFromDocumentWithName:(NSString*)name {
    NSFileWrapper *fileWrapper = [self.documentFileWrapper.fileWrappers objectForKey:name];
    if (fileWrapper) {
        [self.documentFileWrapper removeFileWrapper:fileWrapper];
        [self updateChangeCount:NSChangeDone];
    }
}

- (NSFileWrapper*) documentFileWrapper {
    if (!_documentFileWrapper) { // New document
        _documentFileWrapper = [[NSFileWrapper alloc] initDirectoryWithFileWrappers:nil];
    }
    return _documentFileWrapper;
}

End of NSFileWrapper fileWrappers example article.

NSFileWrapper fileAttributes example in Objective C (iOS).


NSFileWrapper fileAttributes

Returns a file wrapper’s file attributes.

- (NSDictionary *)fileAttributes

Return Value of [NSFileWrapper fileAttributes]
File attributes, in a dictionary of the same sort as that returned by attributesOfItemAtPath:error: (NSFileManager).

NSFileWrapper fileAttributes example.
- (BOOL) contentsOfFileWrapper:(NSFileWrapper*)fileWrapper equalContentsAtPath:(NSString*)path {       
    NSDictionary *fileAttrs = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
    NSUInteger fileSize = [attrs fileSize];
    NSUInteger fileWrapperSize = [fileWrapper.fileAttributes fileSize];  // Will return zero if the file wrapper hasn't been written
    if (fileWrapperSize > 0 && fileSize != fileWrapperSize) return NO;

    NSData *fileData = [NSData dataWithContentsOfURL:fileURL];
    NSData *fileWrapperData = fileWrapper.regularFileContents;
    return [fileData isEqualToData:resourceData];
}

End of NSFileWrapper fileAttributes example article.

NSFileWrapper addRegularFileWithContents preferredFilename example in Objective C (iOS).


NSFileWrapper addRegularFileWithContents preferredFilename

Creates a regular-file file wrapper with the given contents and adds it to the receiver, which must be a directory file wrapper.

- (NSString *)addRegularFileWithContents:(NSData *)data preferredFilename:(NSString *)filename

Parameters of [NSFileWrapper addRegularFileWithContents preferredFilename]
data
Contents for the new regular-file file wrapper.
filename
Preferred filename for the new regular-file file wrapper.

Return Value of [NSFileWrapper addRegularFileWithContents preferredFilename]
Dictionary key used to store the new file wrapper in the directory’s list of file wrappers. The dictionary key is a unique filename, which is the same as the passed-in file wrapper's preferred filename unless that name is already in use as a key in the directory's dictionary of children. See “Working With Directory Wrappers” in Application File Management for more information about the file-wrapper list structure.

Discussion of [NSFileWrapper addRegularFileWithContents preferredFilename]
This is a convenience method. The default implementation allocates a new file wrapper, initializes it with initRegularFileWithContents:, sends it setPreferredFilename:, adds it to the directory with addFileWrapper:, and returns what addFileWrapper: returned.

Special Considerations
This method raises NSInternalInconsistencyException if the receiver is not a directory file wrapper.

This method raises NSInvalidArgumentException if you pass nil or an empty value for filename.

NSFileWrapper addRegularFileWithContents preferredFilename example.
- (BOOL)readFromFileWrapper:(NSFileWrapper *)dirWrapper
                     ofType:(NSString *)typeName
                      error:(NSError **)outError
{

    NSFileWrapper *wrapper;
    NSData *data;

    wrapper = [[dirWrapper fileWrappers] objectForKey:@"MainDocument.pdf"];
    data = [wrapper regularFileContents];
    self.pdfData = data;

    wrapper = [[dirWrapper fileWrappers] objectForKey:@"SignatureBitmap.png"];
    data = [wrapper regularFileContents];
    self.signatureBitmapData = data;

    …

    return YES;
}

- (NSFileWrapper *)fileWrapperOfType:(NSString *)typeName
                               error:(NSError **)outError
{
    NSFileWrapper *dirWrapper = [[[NSFileWrapper alloc]
        initDirectoryWithFileWrappers:nil] autorelease];

    [dirWrapper addRegularFileWithContents:self.pdfData
        preferredFilename:@"MainDocument.pdf"];

    [dirWrapper addRegularFileWithContents:self.signatureBitmapData
        preferredFilename:@"SignatureBitmap.png"];

    …

    return dirWrapper;
}

Example of [NSFileWrapper addRegularFileWithContents preferredFilename].
NSFileWrapper *oldFileWrapper = [self.fileWrapper.fileWrappers objectForKey:fileName];
if (oldFileWrapper) [self.fileWrapper removeFileWrapper:oldFileWrapper];

[self.fileWrapper addRegularFileWithContents:[self encodeObject:object]
                           preferredFilename:fileName];

NSFileWrapper addRegularFileWithContents preferredFilename example.
- (NSFileWrapper *)fileWrapperOfType:(NSString *)typeName error:(NSError **)outError
{  
    NSFileWrapper *wrapper = [[[NSFileWrapper alloc] initDirectoryWithFileWrappers:nil] autorelease];
    [wrapper addRegularFileWithContents:[@"please work" dataUsingEncoding:NSUTF8StringEncoding] preferredFilename:@"foobar"];
    NSDictionary *metadata = [NSDictionary dictionaryWithObject:@"0.1" forKey:@"Version"];
    NSString* errorDescription = nil;
    NSData* dictionaryData = [NSPropertyListSerialization dataFromPropertyList:metadata format:NSPropertyListBinaryFormat_v1_0 errorDescription:&errorDescription];
    if(!dictionaryData)
    {
        if(!errorDescription)
            errorDescription = @"Unknown error";
        if(outError)
            *outError = [NSError errorWithDomain:@"YourErrorDomain" code:69 userInfo:[NSDictionary dictionaryWithObject:errorDescription forKey:NSLocalizedDescriptionKey]];
        return nil;
    }
    [wrapper addRegularFileWithContents:dictionaryData preferredFilename:@"Info.plist"];
    return wrapper;
}

End of NSFileWrapper addRegularFileWithContents preferredFilename example article.

NSFileWrapper addRegularFileWithContents example in Objective C (iOS).


NSFileWrapper addRegularFileWithContents

Creates a regular-file file wrapper with the given contents and adds it to the receiver, which must be a directory file wrapper.

- (NSString *)addRegularFileWithContents:(NSData *)data preferredFilename:(NSString *)filename

Parameters
data
Contents for the new regular-file file wrapper.
filename
Preferred filename for the new regular-file file wrapper.

Return Value of [NSFileWrapper addRegularFileWithContents]
Dictionary key used to store the new file wrapper in the directory’s list of file wrappers. The dictionary key is a unique filename, which is the same as the passed-in file wrapper's preferred filename unless that name is already in use as a key in the directory's dictionary of children. See “Working With Directory Wrappers” in Application File Management for more information about the file-wrapper list structure.

Discussion of [NSFileWrapper addRegularFileWithContents]
This is a convenience method. The default implementation allocates a new file wrapper, initializes it with initRegularFileWithContents:, sends it setPreferredFilename:, adds it to the directory with addFileWrapper:, and returns what addFileWrapper: returned.

Special Considerations
This method raises NSInternalInconsistencyException if the receiver is not a directory file wrapper.

This method raises NSInvalidArgumentException if you pass nil or an empty value for filename.

NSFileWrapper addRegularFileWithContents example.
- (BOOL)readFromFileWrapper:(NSFileWrapper *)dirWrapper
                     ofType:(NSString *)typeName
                      error:(NSError **)outError
{

    NSFileWrapper *wrapper;
    NSData *data;

    wrapper = [[dirWrapper fileWrappers] objectForKey:@"MainDocument.pdf"];
    data = [wrapper regularFileContents];
    self.pdfData = data;

    wrapper = [[dirWrapper fileWrappers] objectForKey:@"SignatureBitmap.png"];
    data = [wrapper regularFileContents];
    self.signatureBitmapData = data;

    …

    return YES;
}

- (NSFileWrapper *)fileWrapperOfType:(NSString *)typeName
                               error:(NSError **)outError
{
    NSFileWrapper *dirWrapper = [[[NSFileWrapper alloc]
        initDirectoryWithFileWrappers:nil] autorelease];

    [dirWrapper addRegularFileWithContents:self.pdfData
        preferredFilename:@"MainDocument.pdf"];

    [dirWrapper addRegularFileWithContents:self.signatureBitmapData
        preferredFilename:@"SignatureBitmap.png"];

    …

    return dirWrapper;
}

Example of [NSFileWrapper addRegularFileWithContents].
NSFileWrapper *oldFileWrapper = [self.fileWrapper.fileWrappers objectForKey:fileName];
if (oldFileWrapper) [self.fileWrapper removeFileWrapper:oldFileWrapper];

[self.fileWrapper addRegularFileWithContents:[self encodeObject:object]
                           preferredFilename:fileName];

NSFileWrapper addRegularFileWithContents example.
- (NSFileWrapper *)fileWrapperOfType:(NSString *)typeName error:(NSError **)outError
{  
    NSFileWrapper *wrapper = [[[NSFileWrapper alloc] initDirectoryWithFileWrappers:nil] autorelease];
    [wrapper addRegularFileWithContents:[@"please work" dataUsingEncoding:NSUTF8StringEncoding] preferredFilename:@"foobar"];
    NSDictionary *metadata = [NSDictionary dictionaryWithObject:@"0.1" forKey:@"Version"];
    NSString* errorDescription = nil;
    NSData* dictionaryData = [NSPropertyListSerialization dataFromPropertyList:metadata format:NSPropertyListBinaryFormat_v1_0 errorDescription:&errorDescription];
    if(!dictionaryData)
    {
        if(!errorDescription)
            errorDescription = @"Unknown error";
        if(outError)
            *outError = [NSError errorWithDomain:@"YourErrorDomain" code:69 userInfo:[NSDictionary dictionaryWithObject:errorDescription forKey:NSLocalizedDescriptionKey]];
        return nil;
    }
    [wrapper addRegularFileWithContents:dictionaryData preferredFilename:@"Info.plist"];
    return wrapper;
}

End of NSFileWrapper addRegularFileWithContents example article.

NSFileWrapper addFileWrapper example in Objective C (iOS).


NSFileWrapper addFileWrapper

Adds a child file wrapper to the receiver, which must be a directory file wrapper.

- (NSString *)addFileWrapper:(NSFileWrapper *)child

Parameters
child
File wrapper to add to the directory.

Return Value of [NSFileWrapper addFileWrapper]
Dictionary key used to store fileWrapper in the directory’s list of file wrappers. The dictionary key is a unique filename, which is the same as the passed-in file wrapper's preferred filename unless that name is already in use as a key in the directory’s dictionary of children. See “Working With Directory Wrappers” in Application File Management for more information about the file-wrapper list structure.

Discussion of [NSFileWrapper addFileWrapper]
Use this method to add an existing file wrapper as a child of a directory file wrapper. If the file wrapper does not have a preferred filename, use the setPreferredFilename: method to give it one before calling addFileWrapper:. To create a new file wrapper and add it to a directory, use the addRegularFileWithContents:preferredFilename: method.

Special Considerations
This method raises NSInternalInconsistencyException if the receiver is not a directory file wrapper.

This method raises NSInvalidArgumentException if the child file wrapper doesn’t have a preferred name.

NSFileWrapper addFileWrapper example.
- (NSFileWrapper*) fileWrapperOfType:(NSString *)typeName error:(NSError *__autoreleasing *)outError {
    return self.documentFileWrapper;
}

- (BOOL) readFromFileWrapper:(NSFileWrapper *)fileWrapper ofType:(NSString *)typeName error:(NSError *__autoreleasing *)outError {
    self.documentFileWrapper = fileWrapper;
    return YES;
}

- (void) addFileToDocumentFromURL:(NSURL*)fileURL {
    NSData* fileData = [NSData dataWithContentsOfURL:fileURL];
    NSFileWrapper *fileWrapper = [[NSFileWrapper alloc] initRegularFileWithContents:fileData];
    fileWrapper.preferredFilename = [fileURL lastPathComponent];
    [self.documentFileWrapper addFileWrapper:fileWrapper];
    [self updateChangeCount:NSChangeDone];
}

- (void) removeFileFromDocumentWithName:(NSString*)name {
    NSFileWrapper *fileWrapper = [self.documentFileWrapper.fileWrappers objectForKey:name];
    if (fileWrapper) {
        [self.documentFileWrapper removeFileWrapper:fileWrapper];
        [self updateChangeCount:NSChangeDone];
    }
}

- (NSFileWrapper*) documentFileWrapper {
    if (!_documentFileWrapper) { // New document
        _documentFileWrapper = [[NSFileWrapper alloc] initDirectoryWithFileWrappers:nil];
    }
    return _documentFileWrapper;
}

Example of [NSFileWrapper addFileWrapper].
 if (self.fileWrapper == nil) {
    self.fileWrapper = [[NSFileWrapper alloc] initDirectoryWithFileWrappers:nil];
}

NSDictionary *fileWrappers = [self.fileWrapper fileWrappers];

if (([fileWrappers objectForKey:@"page"] == nil) && (self.text != nil)) {
    NSData *textData = [self.text dataUsingEncoding:NSUTF8StringEncoding];
    NSFileWrapper *textFileWrapper = [[NSFileWrapper alloc] initRegularFileWithContents:textData];
    [textFileWrapper setPreferredFilename:@"page"];
    [self.fileWrapper addFileWrapper:textFileWrapper];
}

if (([fileWrappers objectForKey:@"pageSettings"] == nil) && (self.pageSettings != nil)) {
    NSData *settingsData = [NSKeyedArchiver archivedDataWithRootObject:self.pageSettings];
    NSFileWrapper *settingsWrapper = [[NSFileWrapper alloc] initRegularFileWithContents:settingsData];
    [settingsWrapper setPreferredFilename:@"pageSettings"];
    [self.fileWrapper addFileWrapper:settingsWrapper];
}

End of NSFileWrapper addFileWrapper example article.