将任何数据类型转换为NSData,然后再返回

时间:2013-11-08 04:18:18

标签: objective-c core-data ios7 nsdata multipeer-connectivity

我正在开发一个应用程序,您可以通过Multipeer Connectivity将文本,图像或联系人发送到另一台设备。然后它将保存在第二个设备的核心数据中。

我所做的是将数据作为NSDictionary发送并再次转换回来。所以我在接收设备上留下了一个NSDictionary。那怎么样,我可以保存对象@" objectData"核心数据?

我希望能与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];

我并不特别想要if,else if语句来确定如何转换核心数据,因为它会在我显示数据时重复。锄头我能做到吗?我目前正在使用NSKeyedArchiver类型的错误,我不确定为什么,因此它被注释掉了。

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:17)

Try this link for understand how its work

您可以为符合NSCoding(或NSSecureCoding)协议的任何对象获取NSData:

NSData *data=[NSKeyedArchiver archivedDataWithRootObject:yourObject];

此行从NSData

创建一个对象
TestClass *objTest=[NSKeyedUnarchiver unarchiveObjectWithData:yourData];

UIImageNSString符合NSCoding,但对于ABPerson,您需要使用返回vCardRepresentation的{​​{1}}。< / p>