领域获得最后n个结果

时间:2016-07-27 13:08:28

标签: ios objective-c cocoa realm

如何从RLMResults获得最后/前n个结果?

我认为你可以转换为NSArray而不是- (NSArray *)subarrayWithRange:(NSRange)range;但是如果RLMResults计算很多,这是不好的方法。

你也可以这样做:

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)]];

但这就像拐杖。

也许用谓词,但无法弄清楚如何?

修改

最终解决方案:

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]];
    }
}

1 个答案:

答案 0 :(得分:0)

为什么不循环RLMResults

使用以下Realm模型

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

和这段代码:

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);

这将记录以下内容:

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}"
)