34
32

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

自前のクラスのインスタンスを NSUserDefaults なんかで保存して置きたいとき

34
Posted at

自前のクラスでNSCodingプロトコルを採用する

encodeWithCoder と initWithCoder を以下のように実装する。

Hoge.h

@interface Hoge:NSObject <NSCoding>

@end

Hoge.m

@implementation Hoge {
	NSString *_hoge;
}

- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:_hoge forKey:@"hoge"];
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super init];
    if (self){
        _hoge = [aDecoder decodeObjectForKey:@"hoge"];
    }
    return self;
}

@end

インスタンスをシリアライズして NSUserDefaults に保存する

シリアライズする時は [NSKeyedArchiver archivedDataWithRootObject:(id)id] を使う。

Save.m

@implementation Save 

	- (void)save{
		Hoge *_hoge = [[Hoge alloc] init];
		NSData *data = [NSKeyedArchiver archivedDataWithRootObject:_hoge];
		NSUserDefaults *userDefaults = [NSUserDefaults 	standardUserDefaults];
		[userDefaults setObject:data forKey:@"hoge"];
		[userDefaults synchronize];
	}

@end

NSUserDefaultsからインスタンスを取り出してデシリアライズする

デシリアライズする時は [NSKeyedUnarchiver unarchiveObjectWithData:(NSData *)data]を使う。

Load.m

@implementation Load 

	- (void)load{
		NSUserDefaults *userDefaults = [NSUserDefaults 	standardUserDefaults];
		NSData *data = [userDefaults dataForKey:@"hoge"];
		Hoge *_hoge = [NSKeyedUnarchiver unarchiveObjectWithData:data]
	}

@end

34
32
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
34
32

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?