Search code examples
iosobjective-cxcodecocoa-touchnsdata

how can convert an object to NSData in objc


Right now, I have a class assuming it's class User ... .. I have an instance User * admin = [[User alloc]init];

I now need to convert this admin into NSData,

Is there any way to do so?

Thanks in advance.


Solution

  • You can get the NSData for any object conforming to the NSCoding or NSSecureCoding protocol:

    NSData *data=[NSKeyedArchiver archivedDataWithRootObject:yourObject];
    

    Converting again to actual form using unarchiveObjectWithData:

    CustomCls *obj = [NSKeyedUnarchiver unarchiveObjectWithData:data];