ios--archive through runtime, reverse archive

Source: Internet
Author: User

With runtime, no matter how many attributes the model has, it can be done with a few lines of code.

Assume that the person class has more than N attributes, but (write 3 of them here)

. h

#import <Foundation/Foundation.h>

@interface person:nsobject <nscoding>

@property (nonatomic, assign) int age ;

@property (nonatomic, assign) int height;

@property (nonatomic, copy) nsstring *name;

@end

. m

#import "Person.h"

#import <objc/runtime.h>

#import <objc/message.h>

@implementation Mjperson

-(void) Encodewithcoder: (nscoder *) Encoder

{

unsigned int count = 0;

Ivar *ivars = class_copyivarlist ([person class], &count);

For (int i = 0; i<count; i++) {

Remove the member variables corresponding to the I position

Ivar Ivar = ivars[i];

View member Variables

const Char *name = ivar_getname (Ivar);

// archive

nsstring *key = [nsstring stringwithutf8string:name];

id value = [self valueforkey:key];

[Encoder Encodeobject:value Forkey:key];

}

Free (ivars);

}

-(ID) Initwithcoder: (nscoder *) Decoder

{

if (self= [Super Init]) {

unsigned int count = 0;

Ivar *ivars = class_copyivarlist ([person class], &count);

For (int i = 0; i<count; i++) {

Remove the member variables corresponding to the I position

Ivar Ivar = ivars[i];

// View member variables

const Char *name = ivar_getname (Ivar);

// archive

nsstring *key = [nsstring stringwithutf8string:name];

id value = [decoder decodeobjectforkey:key];

// set to member variable body

[self setvalue:value Forkey:key];

}

Free (ivars);

}

return self;

}

@end

After this writing, regardless of the number of properties, runtime can complete the model properties of the archive and solution, is not very convenient.

Of course, you can also draw the code inside the. h and. m macro, so that later you want to implement the storage of complex objects only two lines of code can be done.

ios--archive through runtime, reverse archive

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.