将任何数据类型转换为NSData并再次返回 [英] 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.
我所做的是以NSDictionary的形式发送数据并将其重新转换。所以我留在接收设备上的NSDictionary。那么,我可以将对象的@objectData的键保存到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?
我想要使用NSString,UIImage& ABPerson。
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];
我不是特别想做if,else if语句来决定如何转换它的核心数据,因为它将在我显示数据时重复。呃,我可以吗?我目前得到的NSKeyedArchiver类型的错误,我不确定为什么,因此它被注释掉。
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.
任何帮助将非常感激!
推荐答案
您可以为符合 NSCoding的任何对象获取NSData
(或 NSSecureCoding
)协议:
You can get NSData for any object conforming to the NSCoding
(or NSSecureCoding
) protocol:
NSData *data=[NSKeyedArchiver archivedDataWithRootObject:yourObject];
此行从 NSData
/ p>
this line creates an object from NSData
TestClass *objTest=[NSKeyedUnarchiver unarchiveObjectWithData:yourData];
UIImage
NSString 符合 NSCoding
,但对于 ABPerson
,您需要使用 vCardRepresentation
其返回 NSData
。
UIImage
and NSString
conform to NSCoding
, but for ABPerson
you'll need to use the vCardRepresentation
which returns NSData
.
这篇关于将任何数据类型转换为NSData并再次返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!