Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
441 views
in Technique[技术] by (71.8m points)

objective c - Convert any Data Type into NSData and back again

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...