Vignesh Vignesh - 6 months ago 132
iOS Question

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.

Answer

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...