How to create a custom file type that holds text and images?
I know this is going to be somewhat hard to answer, but I need to save text and images into a single file (like photoshop does). Should I make a custom file type, or is there another way to do this?
If I need a custom file type, would somebody please give me link to something that may help me make the file type store the data properly? If there is another way, how can I do t开发者_开发知识库his?
NOTE: I am using this in a application that imports three images, and lets users put text over them, so I may not be able to get the information needed to store the images as text in any way. If it is what I have to do, I will need a link to some helpful information.
An easy way to save objects to a file is to add them to an NSDictionary
and then use NSArchiver
to archive the dictionary into data.
For example in a document based app:
- (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError {
if ([typeName isEqualToString:@"YourTypeName"]) {
//Create a Dictionary
NSMutableDictionary *dictToSave = [NSMutableDictionary dictionary];
//Add the first image to the dictionary
[dictToSave setObject:image1 forKey:@"Image1"];
//Add the first image's text
[dictToSave setObject:image1text forKey:@"Image1Text"];
//etc.
[dictToSave setObject:image2 forKey:@"Image2"];
[dictToSave setObject:image2text forKey:@"Image2Text"];
[dictToSave setObject:image3 forKey:@"Image3"];
[dictToSave setObject:image3text forKey:@"Image3Text"];
//Return the archived data
return [NSArchiver archivedDataWithRootObject:dictToSave];
}
//Don't generate an error
outError = NULL;
return nil;
}
To read this data, just unarchive the dictionary and set the objects:
- (BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName
error:(NSError **)outError {
if ([typeName isEqualToString:@"MyTypeName"]) {
NSMutableDictionary *readDict =
[NSUnarchiver unarchiveRootObjectWithData:data];
image1 = [readDict objectForKey:@"Image1"];
image1text = [readDict objectForKey:@"Image1Text"];
image2 = [readDict objectForKey:@"Image2"];
image2text = [readDict objectForKey:@"Image2Text"];
image3 = [readDict objectForKey:@"Image3"];
image3text = [readDict objectForKey:@"Image3Text"];
}
outError = NULL;
return YES;
}
You will also need to define your custom file type in your app's plist file.
精彩评论