3

所以我想将我的对象归档到应用程序沙箱文档目录中。我从 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");
    }
}
4

1 回答 1

2

您正在保存到NSDocumentationDirectory而不是 NSDocumentDirectory

代替

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

  NSArray *documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
于 2013-05-30T04:03:53.633 回答