简体   繁体   中英

How to use Primary key in Realm in iOS (Objective c)

I Declared email as primary key in a Realm model.

+ (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];
}

After entering a duplicate email app crashes.

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

How to user Primary key in Realm?

How to prevent this crash?

Please help me.

use try... catch to handle exception like

    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];
         }
     }

As suggested by @Konstantin, you can also use [realm addOrUpdateObject:employeeInfo]; to update your data with primary key...

Primary key means that this is unique key though all entities. If keys are not unique, Realm crashes.

That is documentation: Override +primaryKey to set the model's primary key. Declaring a primary key allows objects to be looked up and updated efficiently and enforces uniqueness for each value. Once an object with a primary key is added to a Realm, the primary key cannot be changed.

In your case it's better to create new entity in realm and do migration to this new entity.

Or you can just do dirty hack: add new property and write emails in it, and in email (which is Primary Key) write any unique value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM