使用NSCoding的iOS归档对象失败

时间:2013-05-30 03:44:37

标签: ios nskeyedarchiver nscoding

所以我想将我的对象存档到app sandbox文档目录中。我从Big Nerd Ranch的iOS编程中复制了大部分代码,所以我看不出可能出错的地方。无论如何,我可以诊断过程的哪个部分不起作用,因为它们中没有出现任何错误,但仍然无法保存。这是我的目标代码。

@interface Post : NSObject <NSCoding>
{
    NSString *title;
    NSString *date;
    NSString *content;
    NSString *type;
    UIImage *image;
    NSString *timestamp;
}

@property (nonatomic) NSString *title;
@property (nonatomic) NSString *date;
@property (nonatomic) NSString *content;
@property (nonatomic) NSString *type;
@property (nonatomic) UIImage *image;
@property (nonatomic) NSString *timestamp;

@end


@implementation Post
@synthesize title;
@synthesize  date;
@synthesize content;
@synthesize type;
@synthesize image;
@synthesize timestamp;
#pragma mark - NSCoding Protocol
- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:title forKey:@"title"];
    [aCoder encodeObject:date forKey:@"date"];
    [aCoder encodeObject:content forKey:@"content"];
    [aCoder encodeObject:type forKey:@"type"];
    [aCoder encodeObject:image forKey:@"image"];
    [aCoder encodeObject:timestamp forKey:@"timestamp"];
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    if (self){
        [self setTitle:[aDecoder decodeObjectForKey:@"title"]];
        [self setDate:[aDecoder decodeObjectForKey:@"date"]];
        [self setContent:[aDecoder decodeObjectForKey:@"content"]];
        [self setType:[aDecoder decodeObjectForKey:@"type"]];
        [self setImage:[aDecoder decodeObjectForKey:@"image"]];
        [self setTimestamp:[aDecoder decodeObjectForKey:@"timestamp"]];
    }
    return self;
}

我使用具有以下方法的商店保存存档

- (NSString *)itemArchivePath
{
    NSArray *documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);

    //Get one and only document directory form that list
    NSString *documentDirectory = [documentDirectories objectAtIndex:0];
    return [documentDirectory stringByAppendingPathComponent:@"posts.archive"];
}

- (BOOL)saveChanges
{
    //return success of failure
    NSString *path = [self itemArchivePath];
    NSLog(@"save path = %@",path);
    return [NSKeyedArchiver archiveRootObject:allPosts toFile:path];
}

我在applicationDidEnterBackground中调用了save方法来保存。

- (void)applicationDidEnterBackground:(UIApplication *)application
{    
    BOOL success = [[PostStore sharedStore] saveChanges];
    if (success) {
        NSLog(@"Saved all Posts");
    } else {
        NSLog(@"Could not save any Posts");
    }
}

1 个答案:

答案 0 :(得分:2)

您要保存到 NSDocumentationDirectory 而不是 NSDocumentDirectory

替换

   NSArray *documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);  

  NSArray *documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);