Objective-C
iOS
Realm

RealmとObjective-CでAutoincrement

RealmでAutoincrement

valueForKeyPathで最大値を出して1を加算して返します。
valueForKeyPathはNSNumberで返ってきます。

Fruit *fruit = [[Fruit alloc] init];    

fruit.fid = [Fruit _addAutoincrementNum:@"fid"];
fruit.name = @"みかん";
fruit.price = 150;
[realm beginWriteTransaction];    
[Fruit createOrUpdateInDefaultRealmWithValue:fruit];    
[realm commitWriteTransaction];

@interface RLMObject (ex)

    +(int)_addAutoincrementNum:(NSString*)primaryKey;

@end

@implementation RLMObject (ex)

+(int)_addAutoincrementNum:(NSString*)primaryKey{

    RLMResults* model = [self allObjects];

    NSNumber* autoincrementNum = [model valueForKeyPath:[NSString stringWithFormat:@"@max.%@",primaryKey]];

    int autoincrementNum_int = [(NSNumber*)autoincrementNum intValue] + 1;

    return autoincrementNum_int;
}

@end

@interface Fruit : RLMObject

  @property NSInteger fid;
  @property NSString *name;
  @property NSInteger price;

@end
@implementation Fruit
    +(NSString *)primaryKey {
        return @"fid";
    }
@end