在重新启动iOS之前,此保存的数据似乎无法访问

时间:2014-09-11 14:21:18

标签: ios objective-c uitableview

我有一个自定义NSCoding类,可以在必要时存储和检索自己。但是,在向其中的自定义Person对象数组提供一个条目并重新启动应用程序然后再给出另一个对象之前,它不会将数据提供给我的表视图。然而,第一个消失了。

之后,似乎加载好了。

这是类

的实现
#import "DataStorage.h"

@implementation DataStorage


@synthesize arrayOfPeople = _arrayOfPeople;

+ (DataStorage *)sharedInstance
{
    static DataStorage *state = nil;
    if ( !state )
    {
        NSData *data =[[NSUserDefaults standardUserDefaults] objectForKey:@"DataStorageBank"];

        if (data)
        {
            state = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        }
        else
        {
            state = [[DataStorage alloc] init];
        }
    }
    return state;
}

- (instancetype)initWithCoder:(NSCoder *)decoder
{
    self = [self init];
    if (self) {


        if ([decoder decodeObjectForKey:@"DataStoragePeopleArray"]) {
            _arrayOfPeople = [[decoder decodeObjectForKey:@"DataStoragePeopleArray"] mutableCopy];
        } else {
            _arrayOfPeople = [[NSMutableArray alloc] init];
        }



    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:_arrayOfPeople forKey:@"DataStoragePeopleArray"];
}

- (void)save
{
    NSData *appStateData = [NSKeyedArchiver archivedDataWithRootObject:self];
    [[NSUserDefaults standardUserDefaults] setObject:appStateData forKey:@"DataStorageBank"];
}


@end

我将对象添加到_arrayOfPeople,如下所示:

Person *person = [[Person alloc] initWithFirstName:firstName personSurname:surname personCompay:company personPosition:position personEmail:email personMobile:mobile personProduct:product];

        [[DataStorage sharedInstance].arrayOfPeople addObject:person];
        [[DataStorage sharedInstance] save];

然后将它们加载到表格视图中:

Person *personAtIndex = [[DataStorage sharedInstance].arrayOfPeople objectAtIndex:indexPath.row];
    [_arrayOfPeople addObject:personAtIndex];
    cell.textLabel.text = personAtIndex.firstName;
    cell.detailTextLabel.text = personAtIndex.surname;

将它们加载到表视图中的方法是

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

1 个答案:

答案 0 :(得分:1)

您似乎只在_arrayOfPeople中初始化initWithCoder:。但是,如果您的数据已经存在于用户默认值中,则使用state = [[DataStorage alloc] init]初始化您的共享实例。这不会调用initWithCoder:,因此_arrayOfPeoplenil,直到您再次保存并加载,最后将其初始化为[[NSMutableArray alloc] init]。要解决此问题,请将_arrayOfPeople = [[NSMutableArray alloc] init]移出initWithCoder:并移至init。 (您也可以将其移至sharedInstance,但在init中更有意义,因为它不是特定于配置共享实例。)

不相关,但也请确保您同步。

- (void)save
{
    NSData *appStateData = [NSKeyedArchiver archivedDataWithRootObject:self];
    [[NSUserDefaults standardUserDefaults] setObject:appStateData forKey:@"DataStorageBank"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}