Realm-cocoa: How to get all objects from RLMResults ?

Created on 4 Nov 2015  Â·  6Comments  Â·  Source: realm/realm-cocoa

  • (RLMObjectType)objectAtIndex:(NSUInteger)index;
  • (nullable RLMObjectType)firstObject;
  • (nullable RLMObjectType)lastObject;

but i can't find allObjects.
example
// 使用断言字符串查询
RLMResults *tanDogs = [Dog objectsWhere:@"color = '棕黄色' AND name BEGINSWITH '大'"];
// 使用 NSPredicate 查询
NSPredicate *pred = [NSPredicate predicateWithFormat:@"color = %@ AND name BEGINSWITH %@",
@"棕黄色", @"大"];
tanDogs = [Dog objectsWithPredicate:pred];

How can i get an array from tanDogs?

T-Help

Most helpful comment

For Swift see also https://github.com/realm/realm-cocoa/issues/1046#issuecomment-143804257.
As you're using Objective-C here is the variant how you can achieve the same with RLMResults:

@interface RLMResults (ToArray)
- (NSArray *)toArray;
@end

@implementation RLMResults (ToArray)

- (NSArray *)toArray {
    NSMutableArray *array = [NSMutableArray new];
    for (RLMObject *object in results) {
        [array addObject:object];
    }
    return array;
}

@end

Note: That will pull all instances into memory, while they are lazily instantiated on demand when you're accessing them through RLMResults and they get auto-updated on changes.

All 6 comments

I created this extension to add toArray to Results collections:

import RealmSwift

extension Results {

    func toArray<T>(ofType: T.Type) -> [T] {
        var array = [T]()
        for result in self {
            if let result = result as? T {
                array.append(result)
            }
        }
        return array
    }

}

For Swift see also https://github.com/realm/realm-cocoa/issues/1046#issuecomment-143804257.
As you're using Objective-C here is the variant how you can achieve the same with RLMResults:

@interface RLMResults (ToArray)
- (NSArray *)toArray;
@end

@implementation RLMResults (ToArray)

- (NSArray *)toArray {
    NSMutableArray *array = [NSMutableArray new];
    for (RLMObject *object in results) {
        [array addObject:object];
    }
    return array;
}

@end

Note: That will pull all instances into memory, while they are lazily instantiated on demand when you're accessing them through RLMResults and they get auto-updated on changes.

results - > self, i guess?
for (RLMObject *object in results)

of course )

I'd suggest to also give a type hint to the category like:

@interface RLMResults<RLMObjectType: RLMObject *> (ToArray)

- (NSArray<RLMObjectType> *)toArray;

@end
  • (NSMutableArray *)getEmployeesArray {
    RLMResults *employees = [Employee allObjects];
    NSMutableArray *employeeArray = [employees valueForKey:@"self"];
    return employeeArray;
    }
Was this page helpful?
0 / 5 - 0 ratings