silversam
silversam

Reputation: 127

How could I encode an Objective C object instance as a string?

I know there are various ways of archiving objects in objective-c, but is there some way which I can use to turn an object in Objective-C into a string which I can store in a txt file (amongst other data) and then extract from the file to recreate the same object instance again efficiently?

Thanks in advance

Upvotes: 0

Views: 431

Answers (1)

Joseph El Khoury
Joseph El Khoury

Reputation: 516

It's not recommended to do this.

Why don't you save the object into NSDefaults and extract if from there whenever you want? It's very simple and efficient.

Here is an example. Let's say you have a User object defined as below

User.h

@interface User : NSObject

@property (nonatomic, strong) NSNumber *id;
@property (nonatomic, strong) NSString *first_name;
@property (nonatomic, strong) NSString *last_name;

@end

User.m

#import "User.h"

@implementation User

-(void)encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:id forKey:@"id"];
    [encoder encodeObject:first_name forKey:@"first_name"];
    [encoder encodeObject:last_name forKey:@"last_name"];
}

-(id)initWithCoder:(NSCoder *)decoder {
    if (self = [super init]) {
        self.id = [decoder decodeObjectForKey:@"id"];
        self.first_name = [decoder decodeObjectForKey:@"first_name"];
        self.last_name = [decoder decodeObjectForKey:@"last_name"];
    }
}

- (id)initWith:(User *)obj {
    if (self = [super init]) {
        self.id = obj.id;
        self.first_name = obj.first_name;
        self.last_name = obj.last_name;
    }
}

@end

Whenever you want to save the object, you can do something like that

//Save the user object
User *user = [[User alloc] init];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:user];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:data forKey:@"YOUR_KEY"];
[defaults synchronize];

//Get the user object
NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:@"YOUR_KEY"];
User *user = [[User alloc] initWith:[NSKeyedUnarchiver unarchiveObjectWithData:data]];

Upvotes: 1

Related Questions