我不明白爲什麼previousArrays
返回(null)
,我想保存一個包含bezier路徑和它的顏色的類。返回到應用程序時未保存NSCoding數據?
代碼:(touchesEnded
被調用後,會創建一個路徑,並保存在內存中。當我回來與initWithCoder
應用,previousArrays
是(null)
):
-(id)initWithCoder:(NSCoder *)aDecoder{
if (!(self=[super initWithCoder:aDecoder])) return nil;
CGContextRef context = UIGraphicsGetCurrentContext();
NSArray *previousArrays = [SaveData loadDict];
NSLog(@"previousArrays : %@", previousArrays);//***HERE*** : return (null)
for (id object in previousArrays){
//for (NSDictionary*dict in previousArrays){
NSLog(@"obj %@", [[object class] description]);
//...
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
UIBezierPath *bezierPath = [UIBezierPath bezierPathWithCGPath:myPath];//nscoding compliant
DataForPath *firstPath = [[DataForPath alloc] init];
firstPath.path = bezierPath;
firstPath.colorInArray = @(currentColor);
NSLog(@"touchEnded, firstPath : %@", firstPath);
NSDictionary *dict = @{@"firstPath":firstPath};
[SaveData saveDict:dict];
}
@implementation SaveData
static NSString* kMyData = @"data1";
+ (void) saveDict:(NSDictionary*) dict{
NSLog(@"saving data...");
//retrieve previous data
NSData *previousData = [[NSUserDefaults standardUserDefaults] objectForKey:kMyData];
NSMutableArray *previousArray = [[NSKeyedUnarchiver unarchiveObjectWithData:previousData] mutableCopy];
[previousArray addObject:dict];
//add new data, and save
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:previousArray];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:kMyData];
//NSLog(@"%@", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
}
+(NSArray*) loadDict {
NSLog(@"loading data...");
NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:kMyData];
NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:data];
return array;
}
#import <Foundation/Foundation.h>
@import UIKit;
@interface DataForPath : NSObject <NSCoding>
@property (nonatomic, strong) UIBezierPath* path;
@property (nonatomic, strong) NSNumber *colorInArray;
@end
@implementation DataForPath
- (id)initWithCoder:(NSCoder *)decoder{
if (!(self = [super init])) return nil;
self.path = [decoder decodeObjectForKey:@"path"];
self.colorInArray = [decoder decodeObjectForKey:@"colorInArray"];
return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder{
[encoder encodeObject:self.path forKey:@"path"];
[encoder encodeObject:self.colorInArray forKey:@"colorInArray"];
}
此外,有沒有一種方法查看NSUserDefault中的內容,例如「prettyjson」格式? -dictionaryRepresentation
返回一些數字像<124d1f>
貴'DataForPath'類實現'NSCoding'? – Chris
@Chris嗨克里斯,是的,代碼如下,當您向下滾動時,DataForPath:NSObject –
Paul
您還應該符合['NSSecureCoding'協議](https://developer.apple.com/library/ios/文檔/基礎/參考/ NSSecureCoding_Protocol_Ref/index.html)在iOS 6和更高版本中可用。 – jww