Teja Nandamuri
Teja Nandamuri

Reputation: 11201

How to add auto increment value to realm

I have recently moved from core data to realm. In core data I have auto increment pk for each record that is inserted.

In the realm I couldn't find such thing as auto increment.

At the moment I'm using uuid as pk.

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

I still need to have a reference to old pk, so I have added a new field oldPK to realm, so I can use this to reference the other sqlite tables.This is not a long term solution. I'm looking for short term solution till I migrate completely from sqlite to Realm.

Right now my approach is to get the largest value from the existing oldPk values in the db, and increment it for newly added record.

Is there any better of adding auto increment to Realm model ?

Upvotes: 1

Views: 1077

Answers (1)

ninjaproger
ninjaproger

Reputation: 2044

Realm hasn't any auto incremental primary keys. You should set it for each record. You can use a unique primary key for each record:

[NSUUID UUID].UUIDString; 

or if you want to make primary keys be successively, you can query all records, sort them by primary keys, get the latest record's primary key, increment it and use as a primary key for a new record:

RLMResults<YourRecordClass *> *records = [[YourRecordClass allObjects] sortedResultsUsingKeyPath:@"uuid" ascending:YES];
NSInteger newPrimaryKey = [records lastObject].uuid + 1;
YourRecordClass *newRecord = [[YourRecordClass alloc] init];
newRecord.uuid = newPrimaryKey;

RLMRealm *realm = [RLMRealm defaultRealm];
[realm beginWriteTransaction];
[realm addObject:author];
[realm commitWriteTransaction];

Upvotes: 1

Related Questions