I'm working on an app where you can send either a text, image or a contact over Multipeer Connectivity to another device. It will then save in the second device's Core Data.
What I do is send the data over as an NSDictionary and convert it back again. So I am left with an NSDictionary on the receiving device. How then, can I save the object for the key of @"objectData" to Core Data?
I'd like it to work with NSString, UIImage & ABPerson.
// Create a new object in the managed object context.
Received *receivedData = [NSEntityDescription insertNewObjectForEntityForName:@"Received" inManagedObjectContext:self.managedObjectContext];
// Assign the properties based on what was input in the textfields.
// Check what type it is
NSString *dataType = [dictionary objectForKey:@"type"];
receivedData.type = dataType;
// Determine what type of data was passed over...
if ([dataType isEqualToString:@"Photo"])
{
receivedData.object = UIImageJPEGRepresentation([dictionary
objectForKey:@"object"], 0.5f);
NSLog(@"A photo saved in core data");
}
else
{
//receivedData.object = [NSKeyedArchiver archivedDataWithRootObject:[dictionary objectForKey:@"object"]];
receivedData.object = [[dictionary objectForKey:@"object"] dataUsingEncoding:NSUTF8StringEncoding];
}
// Save the managed object context.
NSError *error = nil;
[self.managedObjectContext save:&error];
I don't particularly want to do the if, else if statements to determine how to convert it core data as it would then be repeated when I display the data. Hoe else can I do it? I am currently getting errors with the NSKeyedArchiver type which I am unsure why and hence it is commented out.
Any help would be much appreciated!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…