Nik Kov Nik Kov - 4 months ago 20
iOS Question

Realm get last n results

How to get last/first n results from RLMResults?

I think you can transform to NSArray and than do

- (NSArray *)subarrayWithRange:(NSRange)range;
but this is bad way if RLMResults count a lot.

Also you can do something like:

self.arrayOfSubscriptedResults = [NSMutableArray new];
RLMResults *results = [[ModelRO objectsWhere:@"smth == 21"] sortedResultsUsingProperty:@"property" ascending:NO];
[self.arrayOfSubscriptedResults addObject: [results lastObject]];
[self.arrayOfSubscriptedResults addObject: [results objectAtIndex:(results.count - 1)]];
[self.arrayOfSubscriptedResults addObject: [results objectAtIndex:(results.count - 2)]];


but this like a crutch.

Maybe with predicate, but can't figure out how?

EDIT:

Final solution:

RLMResults *results = getRealmResultsHere;

int count = results.count;
int numberOfFirstObjects = 3;

if (count > 0)
{
self.mutableArray = [NSMutableArray arrayWithCapacity: numberOfFirstObjects];

for (NSUInteger index = 0; (self.mutableArray.count < numberOfFirstObjects) && (count > index); index++)
{
[self.mutableArray addObject:results[index]];
}
}

Answer

Why not loop over the RLMResults?

With the following Realm model

@interface Dog : RLMObject
@property NSString *name;
@property NSInteger age;
@end
@implementation Dog
@end

and this code:

RLMRealm *realm = [RLMRealm defaultRealm];
[realm transactionWithBlock:^{
    [Dog createInRealm:realm withValue:@[@"Rex", @1]];
    [Dog createInRealm:realm withValue:@[@"Fido", @2]];
    [Dog createInRealm:realm withValue:@[@"Einstein", @3]];
    [Dog createInRealm:realm withValue:@[@"Ruffles", @4]];
}];

RLMResults *allDogs = [Dog allObjects];
NSUInteger numberOfDogs = 3;
NSMutableArray *last3Dogs = [NSMutableArray arrayWithCapacity:numberOfDogs];
for (NSUInteger index = allDogs.count - numberOfDogs; last3Dogs.count < numberOfDogs; index++) {
    [last3Dogs addObject:allDogs[index]];
}
NSLog(@"last 3 dogs: %@", last3Dogs);

This would log the following:

last 3 dogs: (
    "Dog {\n\tname = Fido;\n\tage = 2;\n}",
    "Dog {\n\tname = Einstein;\n\tage = 3;\n}",
    "Dog {\n\tname = Ruffles;\n\tage = 4;\n}"
)