Search code examples
objective-crealm

Correct way to retrieve a single object from Realm database in Objective-C


#import "RLMObject.h"

@interface Product : RLMObject

@property NSInteger productId;
@property NSString *name;

@end

@implementation Product

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

@end

fetch all objects:

RLMResults<Product *> *xx = [Product allObjects];

but how to get single object (not array) by its primary key?


Solution

  • Any RLMObject subclasses inherits method

    • (nullable instancetype)objectForPrimaryKey:(nullable id)primaryKey;

    So, you can fetch a single object by calling:

    [Product objectForPrimaryKey: @""];