Search code examples
objective-crealmrlmarray

How to sort RLMArray using property?


I'm trying to sort an RLMArray using its property but I am getting the error:

This method may only be called on RLMArray instances retrieved from an RLMRealm`

 RLMResults *rlmResults  =  [myLog.myRLMArray sortedResultsUsingProperty:@"orderNum" ascending:YES];

Here myLog.myRLMArray is a copy of data I get from the RLMRealm.

and myLog is declared as:

 RLM_ARRAY_TYPE(MyWidgetSet)
@interface MYLogObject : RLMObject
@property RLMArray< MyWidgetSet *>< MyWidgetSet > *myRLMArray;
@end

and my custom class is

#import <Realm/Realm.h>

@interface MyWidgetSet : RLMObject
@property NSString *widgetName;
@property NSString *orderNum;
@end

I found a similar question which was posted 2 years ago. I am hoping for an updated solution for this issue.I'm using Realm 2.1.2


Solution

  • As you can see in the error message, the sortedResultsUsingProperty method can be used only for the object obtained by a query. You should save the object to Realm first. It is the best way to sort RLMArray for a performance.

    Or if you'd like to sort RLMArray that has not been saved to Realm, you can use NSArray. So what you are doing is correct. The only thing is converting RLMArray to NSArray can be written in more simple. Just use valueForKey:@"self", you do not need to iterate all elements.

    NSArray *tempLog = [myLog.myRLMArray valueForKey:@"self"];
    ...