gpt4 book ai didi

带有 NSCoding 的 iOS 归档对象失败

转载 作者:行者123 更新时间:2023-12-04 18:20:32 31 4
gpt4 key购买 nike

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

最佳答案

您正在保存到 NSDocumentationDirectory 而不是 NSDocumentDirectory

替换

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

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

关于带有 NSCoding 的 iOS 归档对象失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16827578/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com