尝试通过NSKeyedArchiver将用户数据保存到文件 - 当我点击保存时,我得到NSInvalidArgumentException

时间:2012-03-30 12:15:52

标签: iphone ios nskeyedarchiver

喜欢将用户个人信息(姓名,电话号码等)保存到文件中,使用:NSKeyedArchiver供以后使用。

点击SaveButton时出现以下错误:

2012-03-30 14:01:11.483 Archive2 [41840:f803] *由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'* - [__ NSArrayM insertObject:atIndex:]:对象不能为零' * 第一次抛出调用堆栈: (0x13c8022 0x1559cd6 0x13b533e 0x13b61f0 0x2917 0x13c9e99 0x1514e 0x150e6 0xbbade 0xbbfa7 0xbb266 0x3a3c0 0x3a5e6 0x20dc4 0x14634 0x12b2ef5 0x139c195 0x1300ff2 0x12ff8da 0x12fed84 0x12fec9b 0x12b17d8 0x12b188a 0x12626 0x1f9d 0x1f05) 终止调用抛出异常(lldb)

h file:

@property (nonatomic, strong) IBOutlet UITextField *vorname;
@property (nonatomic, strong) IBOutlet UITextField *nachname;
@property (nonatomic, strong) IBOutlet UITextField *ausweisNR;
@property (nonatomic, strong) IBOutlet UITextField *serviceNR;
@property (nonatomic, strong) IBOutlet UITextField *telephoneNumber;
@property (nonatomic, strong) NSString *dataFilePath;

-(IBAction)saveData:(id)sender;

m file:

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSFileManager *filemgr;
    NSString *docsDir;
    NSArray *dirPaths;

    filemgr = [NSFileManager defaultManager];

    //Get the documents directory:
    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    docsDir = [dirPaths objectAtIndex:0];

    // Build the path to the data file:
    dataFilePath = [[NSString alloc]initWithString:[docsDir stringByAppendingPathComponent:@"data.archive"]];

    // Check if the file already exist:
    if ([filemgr fileExistsAtPath:dataFilePath]) // File exist so rebuild...
    {
        NSMutableArray *userCredentials;
        userCredentials = [NSKeyedUnarchiver unarchiveObjectWithFile:dataFilePath];

        self.serviceNR.text = [userCredentials objectAtIndex:0];
        self.ausweisNR.text = [userCredentials objectAtIndex:1];
        self.vorname.text = [userCredentials objectAtIndex:2];
        self.nachname.text = [userCredentials objectAtIndex:3];
        self.telephoneNumber.text = [userCredentials objectAtIndex:4];
    }
}



-(IBAction)saveData:(id)sender
{
    NSMutableArray *userCredentials = [[NSMutableArray alloc]init];

    [userCredentials addObject:self.serviceNR.text];
    [userCredentials addObject:self.ausweisNR.text];
    [userCredentials addObject:self.vorname.text];
    [userCredentials addObject:self.nachname.text];
    [userCredentials addObject:self.telephoneNumber.text];
    [NSKeyedArchiver archiveRootObject:userCredentials toFile:dataFilePath];
}

1 个答案:

答案 0 :(得分:1)

您的一个文字字段为空。 你应该先测试它们。

if([self.serviceNR.text length]){
    [userCredentials addObject:self.serviceNR.text];
}

依旧......