Question

Sorry if this is obvious, but I'm struggling with how to extract components from a NSFileWrapper and the docs were not particular enlightening.

I have two wrappers. One holds a simple txt file. The other one holds pageSettings. PageSettings is an NSObject which holds several NSStrings, BOOLs etc. This is my wrapper (based on Apple's Document-Based Application Programming Guide for iOS) and I am now stuck trying to extract the information again:

    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];
}

So my question is how to load the txt file and the pageSettings back into self.text and self.pageSettings?

Do I use - (NSData *)serializedRepresentation? If so, how? Or do I simply reverse it like this:

NSDictionary *fileWrappers = [self.fileWrapper fileWrappers];
self.text = [fileWrappers objectForKey:@"page"];
self.pageSettings = [fileWrappers objectForKey:@"pageSettings"];

I'd be very grateful any explanations. Thanks so much.

Was it helpful?

Solution

NSDictionary *fileWrappers = [self.fileWrapper fileWrappers];

NSFileWrapper *pageWrapper = [fileWrappers objectForKey:@"page"];
NSData *pageData = pageWrapper.regularFileContents;
self.text = [[NSString alloc] initWithData:pageData encoding:NSUTF8StringEncoding];

NSFileWrapper *pageSettingsWrapper = [fileWrappers objectForKey:@"pageSettings"];
NSData *pageSettingsData = pageSettingsData.regularFileContents;
self.pageSettings = [NSKeyedUnarchiver unarchiveObjectWithData:pageSettingsData];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top