gpt4 book ai didi

ios - 如何在 iOS 的 Realm 中使用主键( objective-c )

转载 作者:行者123 更新时间:2023-11-28 19:37:12 25 4
gpt4 key购买 nike

我将电子邮件声明为 Realm 模型中的主键。

+ (NSString *)primaryKey
{
return @"email";
}


- (void)insertUserWithFirstName:(NSString*)firstname lastName: (NSString*)lastname email:(NSString*)email address:(NSString*)address gender:(NSString*)gender mobile:(NSString*)mobile department:(NSString*)department
{
RLMRealm *realm = [RLMRealm defaultRealm];
[realm beginWriteTransaction];

Employee *employeeInfo = [[Employee alloc]init];
employeeInfo.firstName = firstname;
employeeInfo.lastName = lastname;
employeeInfo.email = email;
employeeInfo.address = address;
employeeInfo.gender = gender;
employeeInfo.mobile = mobile;
employeeInfo.department = department;

[realm addObject:employeeInfo];
[realm commitWriteTransaction];
}

输入重复的电子邮件后应用崩溃。

Terminating app due to uncaught exception 'RLMException', reason: 'Can't set primary key property 'email' to existing value .

如何在 Realm 中使用主键?

如何防止这种崩溃?

请帮帮我。

最佳答案

使用try...catch来处理异常

    RLMRealm *realm = [RLMRealm defaultRealm];
@try {
[realm beginWriteTransaction];

Employee *employeeInfo = [[Employee alloc]init];
employeeInfo.firstName = firstname;
employeeInfo.lastName = lastname;
employeeInfo.email = email;
employeeInfo.address = address;
employeeInfo.gender = gender;
employeeInfo.mobile = mobile;
employeeInfo.department = department;
[realm addObject:employeeInfo]; // [realm addOrUpdateObject:employeeInfo];
[realm commitWriteTransaction];
}
@catch (NSException *exception) {
NSLog(@"exception");
if ([realm inWriteTransaction]) {
[realm cancelWriteTransaction];
}
}

正如@Konstantin 所建议的,您还可以使用 [realm addOrUpdateObject:employeeInfo]; 来使用主键更新您的数据...

关于ios - 如何在 iOS 的 Realm 中使用主键( objective-c ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37592555/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com