全体の流れ
1.データを格納しておくカスタムクラスを作る(NSObject<NSCoding>)
2.CKAssetはそのまま保存できないのでNSDataで保存できるようにする
2.NSCodingに必要な物をメソッドを実装する
4. 必要なデータを格納しファイルに保存したりする
//データを格納しておくカスタムクラスを作る
【DataClass.h】
#import <Foundation/Foundation.h>
@import CloudKit;
@interface DataClass : NSObject<NSCoding>{
CKRecord*record;
NSData*photoData;
}
@property(readwrite)CKRecord*record;
@property(readwrite)NSData*photoData;
@end
【DataClass.m】
#import “DataClass.h”
@implementation DataClass
@synthesize record;
@synthesize photoData;
-(id)initWithCoder:(NSCoder *)aDecoder{
self.record=[aDecoder decodeObjectForKey:@”record”];
self.photoData=[aDecoder decodeObjectForKey:@”photoData”];
return self;
}
-(void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:self.record forKey:@”record”];
[aCoder encodeObject:self.photoData forKey:@”photoData”];
}
@end
//データを格納するクラスを準備する
DataClass*dataClass=[[DataClass alloc]init];
NSMutableArray*dataArray=[[NSMutableArray alloc]initWithCapacity:0];
//データを格納する
dataClass.record=record;
CKAsset*asset=[record valueForKey:@”photoAsset”];
dataClass.photoData=[[NSData alloc] initWithContentsOfFile:asset.fileURL.path];
[dataArray addObject:dataClass];
//今回は日付のファイル名で保存するのでその準備
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setLocale:[NSLocale currentLocale]];
[formatter setDateFormat:@”yyyyMMdd”];
//ファイルの作成準備
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString*fileName=[[paths objectAtIndex:0] stringByAppendingFormat:@”/cacheData/%@.dat”,[formatter stringFromDate:selectedDate]];
//ファイルに保存する
[NSKeyedArchiver archiveRootObject:dataArray toFile:fileName];
//ファイルから復元する場合
[dataArray addObjectsFromArray:[NSKeyedUnarchiver unarchiveObjectWithFile:fileName]];