How to Use NSCoding

Let’s say you want to archive or save a object called City. The City.h is declared as below:

1
2
3
4
5
6
7
8
@interface City : NSObject

@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *state;
@property (nonatomic) NSInteger population;
@property (nonatomic, strong) NSString *note;

@end

The first thing you need to do is to make your class confirm to NSCoding protocol. This is simply telling the system,

“Ok, i’m gonna use NSCoding to help archive and unarchive this class.”

Next, you need to add two methods to your City.h, which will actually help you doing the archive and unarchive works.

1
2
3
- (id)initWithCoder:(NSCoder *)aDecoder;

- (void)encodeWithCoder:(NSCoder *)aCoder;

You will need to implement these two methods by yourself, but you will never call these two method manually. We will explain it later. Add implementation of these two methods to City.m,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeObject:self.state forKey:@"state"];
    [aCoder encodeObject:[NSNumber numberWithInteger:self.population] forKey:@"population"];
    [aCoder encodeObject:self.note forKey:@"note"];
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    if (self)
    {
        self.name = [aDecoder decodeObjectForKey:@"name"];
        self.state = [aDecoder decodeObjectForKey:@"state"];
        self.population = [[aDecoder decodeObjectForKey:@"population"] integerValue];
        self.note = [aDecoder decodeObjectForKey:@"note"];
    }
    return self;
}

Comments