0

我无法使用NSUserDefaults. 几天来我一直在尝试不同的代码,但无法做到正确。我已经阅读了有关该主题的所有内容,包括 StackOverflow 中的所有帖子。我知道我很接近,但我真的很感激有人指出我做错了什么。我知道arr在下面的代码中,计数为零,这就是我遇到障碍的地方。我还没有超过那个点。我敢打赌,在阅读我的帖子后 2 分钟内,有人会大笑并指出我的愚蠢错误。

这是相关代码,包括日志:

联系人.h:

 @interface Contacts : NSObject  // <NSCoding>
{
    NSMutableArray *arr;    // 8/21/13
}

联系人.m

- (void)encodeWithCoder:(NSCoder *)aCoder
{
      NSLog(@"In encodeWithCoder");
      NSLog(@"In encodeWithCoder. arr's count is: %i", [arr count]);
    {
       for (int i = 0; i <[arr count]; i++)
       {
            NSLog(@"In encodeWithCoder %@", [arr objectAtIndex:i]);
            NSLog(@"class %@", [arr class]);
       }
     [aCoder encodeObject:arr forKey:@"allContacts"];
    }
}

- (id) initWithCoder:(NSCoder *)aDecoder
{
    NSLog(@"In initWithCoder");
    arr = [aDecoder decodeObjectForKey:@"allContacts"];
    return self;
}

// The following two methods might not even be needed. I copied them from some examples.

- (NSData *)dataOftype:(NSString *)typeName error:(NSError **)outError
{
    return nil;
}

- (BOOL)readFromData:(NSData *)data oftype:(NSString *)typeName error: (NSError **)outError
{
    arr = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    NSLog(@"allContacts is ->%@", [arr mutableCopy]);
    return YES;
}

ContactStore.h

@interface ContactsStore : NSObject <NSCoding>
{
    NSMutableArray *arr;            // 8/21/13
    NSMutableArray *allContacts;    
}

ContactStore.m

    - (void)fetchContactsIfNecessary
{
    NSLog(@"in ContactsStore.m - fetchContactsIfNecessary #1");
    if (!allContacts)
    {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSData *data = [defaults objectForKey:@"allContacts"];
        allContacts = [[NSMutableArray alloc]initWithArray:[NSKeyedUnarchiver    unarchiveObjectWithData:data]];
        for (int i = 0; i <[allContacts count]; i++)
        {
            NSLog(@"In FetchContactsIfNecessary- Gettingfrom NSUserDefaults %@", [allContacts objectAtIndex:i]);
            NSLog(@"In FetchContactsIfNecessary- Gettingfrom NSUserDefaults - class %@", [allContacts class]);
        }
    }

    // If we didn't find one in NSUserDefaults, then create a new one.
    if (!allContacts)
    {
        allContacts = [[NSMutableArray alloc] init];
        NSLog(@"In FetchContactsIfNecessary-We just allocated allContacts");
    }
    NSLog(@"in ContactsStore.m - Leaving fetchContactsIfNecessary2");
}


- (BOOL)saveChanges
{
    for (int i = 0; i <[allContacts count]; i++)
    {
        NSLog(@"In saveChanges %@", [allContacts objectAtIndex:i]);
        NSLog(@"In saveChanges class %@", [allContacts class]);
    }
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    arr = allContacts;   // 8/21/13
        NSLog(@"In saveChanges. arr's count is: %i", [arr count]);
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:arr];
    [defaults setObject:data forKey:@"allContacts"];
    [[NSUserDefaults standardUserDefaults] synchronize];
       NSLog(@"We just synchronized allContacts - I think");
    return 1;
}

日志

2013-08-22 14:13:50.764 ImOK[16979:907] In saveChanges Scott Stringer, (212) 888-1234
2013-08-22 14:13:50.772 ImOK[16979:907] In saveChanges class __NSArrayM
2013-08-22 14:13:50.775 ImOK[16979:907] In saveChanges Sheldon Silver, (212) 987-4321
2013-08-22 14:13:50.781 ImOK[16979:907] In saveChanges class __NSArrayM
2013-08-22 14:13:50.793 ImOK[16979:907] In saveChanges. arr's count is: 2
2013-08-22 14:13:50.795 ImOK[16979:907] In encodeWithCoder
2013-08-22 14:13:50.796 ImOK[16979:907] In encodeWithCoder. arr's count is: 0
2013-08-22 14:13:50.798 ImOK[16979:907] In encodeWithCoder
2013-08-22 14:13:50.799 ImOK[16979:907] In encodeWithCoder. arr's count is: 0
2013-08-22 14:13:50.805 ImOK[16979:907] We just synchronized allContacts - I think

应用程序从后台返回后,姓名和电话号码正确显示,但重新启动应用程序后我只得到四个空值。我预计这是因为arr方法中的计数为零encodeWithCoder,但我不知道如何解决这个问题。

4

1 回答 1

0

你只是编码和解码你的对象。你还没有存储它。要存储它,您需要这样的函数:

- (BOOL)storeBrandOnDevice
{
    NSString *path = [self itemArchivePath];
    NSMutableData *data = [[NSMutableData alloc] init];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [archiver encodeObject:self forKey:@"Contacts"];
    [archiver finishEncoding];
    BOOL dataSaveSuccess = [data writeToFile:path atomically:YES];

    return dataSaveSuccess;
}

从商店中获取它们,如下所示: - (void) getBrandFromStorage {

NSString *path = [self itemArchivePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
    NSData *data = [[NSMutableData alloc] initWithContentsOfFile:path];
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    Contacts* storedContacts = [unarchiver decodeObjectForKey:@"Contacts"];
    [unarchiver finishDecoding];
}

}

这是您缺少的功能:

- (NSString*)itemArchivePath
{

    @try {

        NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString* documentDirectory = [documentDirectories objectAtIndex:0];

        return [documentDirectory stringByAppendingPathComponent:@"items.archive"];
    }
    @catch (NSException *exception) {
        return nil;
    }
}

它可能并不完美,但这是一般概念。

有关 NSCoding 的更多信息,请遵循 Ray Wenderlich 的教程

于 2013-08-22T19:15:53.280 回答