Convert any Data Type into NSData and back again

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-27 02:48:42

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/19851510/convert-any-data-type-into-nsdata-and-back-again

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!