Reputation: 783
How do I convert my NSManagedObject
to NSData
object?
I'm new to Core Data and the Multipeer Connectivity Framework.
I need to transfer data between 2 devices via the Multipeer Connectivity Framework. I understand that I cannot simply transfer via MPC since it requires an NSData object.
Are there any third-party libraries that provides such function?
Upvotes: 3
Views: 1568
Reputation: 33
You should use NSCoding protocol. Using NSKeyedAchiever you can encode your object to NSData. Again If you want decode your original object use NSKeyedUnarchiver.
@interface Test : NSManagedObject <NSCoding>
@property (nonatomic, retain) NSString *title;
@end
@implementation Test
@dynamic title;
- (id)initWithCoder:(NSCoder *)coder {
NSEntityDescription *entity =
[NSEntityDescription entityForName:@"Test" inManagedObjectContext:<YourContext>];
self = [super initWithEntity:entity insertIntoManagedObjectContext:nil];
NSArray * attributeNameArray =
[[NSArray alloc] initWithArray:self.entity.attributesByName.allKeys];
for (NSString * attributeName in attributeNameArray) {
[self setValue:[aDecoder decodeObjectForKey:attributeName] forKey:attributeName];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
[coder encodeObject:self.title forKey:@"title"];
}
@end
//converting to NSData
NSData *archivedObject = [NSKeyedArchiver archivedDataWithRootObject:testObj];
//get your original object
Test *testObj = [NSKeyedUnarchiver unarchiveObjectWithData:archivedObject];
Upvotes: 0
Reputation: 80273
I think NSCoding
is not such a good idea here. The reason is that the objects will not be the same on two different devices due to their internal managed object IDs as well as a myriad of other possible problems that can occur in unexpected syncing scenarios.
I would strongly recommend to take the trouble and convert your object into a NSDictionary
type and then use the standard NSData
APIs on the dictionary (or an array of dictionaries).
Upvotes: 2
Reputation: 8945
try like this You should use NSCoding protocol, then you can encode your object to NSData. Again If you want decode your original object use NSKeyedUnarchiver.
in .h
@interface Testting : NSManagedObject<NSCoding>
and this in .m
NSData *data=[NSKeyedArchiver archivedDataWithRootObject:hereyourObject];
//get your original object
Testting *Obj = [NSKeyedUnarchiver unarchiveObjectWithData:data];
Upvotes: 0