I'm trying to transfer data between 2 devices using bluetooth. I want to convert custom NSObject to NSData.
What is the best way to decode the received NSData into a custom NSObject ?
Thanks!
I'm trying to transfer data between 2 devices using bluetooth. I want to convert custom NSObject to NSData.
What is the best way to decode the received NSData into a custom NSObject ?
Thanks!
You have to use NSCoding. NSCoding is a simple protocol, with two methods: initWithCoder: and encodeWithCoder:. Classes that conform to NSCoding can be serialized and deserialized into data that can be either be archived to disk or distributed across a network.
NSCoding / NSKeyed​Archiver.
Here is tutorial of NSCoding.
Archiving
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:YourClass];
Unarchiving
YourClass *objYourClass = [NSKeyedUnarchiver unarchiveObjectWithData:data];
You can also refer my answer. First you have to create Bean Class and implement initWithCoder: and encodeWithCoder: after that you can Archive NSData from bean class object and Unarchive bean class object from NSData.
My very simple answer
First we have to implement the encodeWithCoder and initWithCoder in NSObject.m and before that I have 2 data(username and password) in NSObject Class.For example I set this.You can understand
- (void)encodeWithCoder:(NSCoder *)encoder
{
//Encode properties, other class variables, etc
[encoder encodeObject:@"Dev" forKey:@"username"];
[encoder encodeObject:@"Test@123" forKey:@"password"];
}
- (id)initWithCoder:(NSCoder *)decoder
{
if((self = [super init]))
{
//decode properties, other class vars
userName = [decoder decodeObjectForKey:@"username"];
passWord = [decoder decodeObjectForKey:@"password"];
}
return self;
}
Then in ViewController.m
For Save
NSObjectClass *className = [[NSObjectClass alloc]init];
NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:className];
[currentDefaults setObject:data forKey:@"DATA"];
[currentDefaults synchronize];
For Retrieve
NSData *data = [currentDefaults objectForKey:@"DATA"];
className = [NSKeyedUnarchiver unarchiveObjectWithData:data];
For More Details Go through My ANSWER