Convert any Data Type into NSData and back again

falky picture falky · Nov 8, 2013 · Viewed 11.3k times · Source

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!

Answer

Jignesh Chanchiya picture Jignesh Chanchiya · Nov 8, 2013

Try this link for understand how its work

You can get NSData for any object conforming to the NSCoding (or NSSecureCoding) protocol:

NSData *data=[NSKeyedArchiver archivedDataWithRootObject:yourObject];

this line creates an object from NSData

TestClass *objTest=[NSKeyedUnarchiver unarchiveObjectWithData:yourData];

UIImage and NSString conform to NSCoding, but for ABPerson you'll need to use the vCardRepresentation which returns NSData.