Can't archive items


#1

in “NSKeyedArchiver and NSKeyedUnarchiver”, it always said “Homepwner[986:60b] Could not save any of the BNRItems”. I check my code a few times. Does anyone have the same problem?

here is my code:
BNRItems.m

[code]- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:self.itemName forKey:@“itemName”];
[aCoder encodeObject:self.serialNumber forKey:@“serialNumber”];
[aCoder encodeObject:self.dateCreated forKey:@“dateCreated”];
[aCoder encodeObject:self.itemKey forKey:@“itemKey”];
[aCoder encodeInt:self.valueInDollars forKey:@“valueInDollars”];

NSLog(@"encoding objects");

}

  • (instancetype)initWithCoder:(NSCoder *)aDecoder
    {
    self = [super init];
    if (self) {
    _itemName = [aDecoder decodeObjectForKey:@“itemName”];
    _serialNumber = [aDecoder decodeObjectForKey:@“serialNumber”];
    _dateCreated = [aDecoder decodeObjectForKey:@“dateCreated”];
    _itemKey = [aDecoder decodeObjectForKey:@“itemKey”];
    _valueInDollars = [aDecoder decodeIntForKey:@“valueInDollars”];
    }
    return self;
    }[/code]

BNRItemStore.m

- (NSString *)itemArchivePath
{
    NSArray *documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [documentDirectories firstObject];
    NSLog(@"%@",[documentDirectory stringByAppendingPathComponent:@"itemsArchive"]);
    
    return [documentDirectory stringByAppendingPathComponent:@"itemsArchive"];
}

- (BOOL)saveChanges
{
    NSString *path = [self itemArchivePath];
    
    BOOL a = [NSKeyedArchiver archiveRootObject:self.privateItems toFile:path];
    
    NSLog(@"archive:%d",a);
    
    return a;
    
}

BNRAppDelegate.m

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    
    BOOL success = [[BNRItemStore sharedStore]saveChanges];
    NSLog(@"%d",success);
    
    if (success) {
        NSLog(@"Saved all of the BNRItems");
    } else {
        NSLog(@"Could not save any of the BNRItems");
    }
    
}

#2

I copy the codes from the book and run it in a previous version of Homepwner, It works now.But I still can not figure out. :confused:


#3

This is where auto-complete can really bite you! The problem was, you used NSDocumentationDirectory instead of NSDocumentsDirectory. Moral of the story is - be very careful that auto-complete is completing what you want.


#4

Thanks a lot. I guess I am not the first one met this problem. I should read the note more carefully. :stuck_out_tongue:


#5

Thanks a lot. I guess I am not the first one met this problem. I should read the note more carefully. :stuck_out_tongue:[/quote]

Not at all! That’s why the comment is there in the book. :slight_smile: