我是Core Data的新手,我正在尝试将其用于保存用户。但是,当我第一次创建用户时,它会插入用户。这似乎没问题。它只被调用一次。
-(void)insertUser: (User *) user{
[self userToModel:user];
NSError *error = nil;
if(![context save:&error]){
NSLog(@"Unable to save managed object context");
}
}
-(UserModel *)userToModel:(User *) user{
UserModel *usermodel = [NSEntityDescription
insertNewObjectForEntityForName:@"UserModel"
inManagedObjectContext:context];
[usermodel setValue:user.username forKey:@"username"];
[usermodel setValue:user.password forKey:@"password"];
[usermodel setValue:user.sessionid forKey:@"sessionid"];
[usermodel setValue:[NSNumber numberWithBool:TRUE] forKey:@"selected"];
[usermodel setValue:[NSNumber numberWithBool:user.beta] forKey:@"beta"];
return usermodel;
}
接下来,我正在获取用户并返回3个用户:2个完全相似的用户和一个零模型。
-(NSMutableArray *)getUsers{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"UserModel"
inManagedObjectContext:context];
NSError *error;
[fetchRequest setEntity:entity];
NSArray *usermodels= [context executeFetchRequest:fetchRequest error:&error];
NSMutableArray *users = [[NSMutableArray alloc] init];
for(UserModel *userModel in usermodels){
User *user = [self userModelToUser:userModel];
[users addObject:user];
}
return users;
}
UserModelToUser:
-(User *)userModelToUser:(UserModel *)usermodel{
User *user = [[User alloc]initWithUsername:usermodel.username
Password:usermodel.password
CSRFToken:usermodel.csrftoken
sessionid:usermodel.sessionid
Beta:[usermodel.beta boolValue]
Selected:[usermodel.selected boolValue]];
return user;
}
SelectUser
-(void)selectUser: (User *)userToSelect OldUser:(User *)oldSelectedUser{
UserModel *oldSelectedUserModel = [self userToModel:oldSelectedUser];
UserModel *newSelectedUsermodel = [self userToModel:userToSelect];
[oldSelectedUserModel setValue:[NSNumber numberWithBool:FALSE] forKey:@"selected"];
[newSelectedUsermodel setValue:[NSNumber numberWithBool:TRUE] forKey:@"selected"];
NSError *saveError;
if (![context save:&saveError]) {
NSLog(@"Changing users failed %@", saveError);
}
}
我已经尝试重新安装该应用,以确保没有旧用户仍然保存或任何东西。任何人都可以帮助我吗?