-1

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!

Bhavesh Nayi
  • 3,626
  • 1
  • 27
  • 42
  • You could make your class NSCoding compliant and use the `NSKeyedArchiver`, or a translation into a JSON (and create a `initWithJSON:` custom init), etc. – Larme Jul 27 '16 at 13:11

2 Answers2

4

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.

Community
  • 1
  • 1
Jayesh Thanki
  • 2,037
  • 2
  • 23
  • 32
0

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

Community
  • 1
  • 1
user3182143
  • 9,459
  • 3
  • 32
  • 39