0

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

Community
  • 1
  • 1
Teja Nandamuri
  • 11,045
  • 6
  • 57
  • 109

2 Answers2

2

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"];
...
kishikawa katsumi
  • 10,418
  • 1
  • 41
  • 53
1

For now I am using NSArray to sort the data. I hope someone would come up with a better way of doing it directly using RLMArray

NSMutableArray *tempLog = [NSMutableArray array];
for (MyWidgetSet *tempSet in myLog.myRLMArray){
    [tempLog addObject:tempSet];
}

and sort using sortedArrayUsingComparator

 NSArray *tempWelLogCopy = [tempLog sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {

        if ([[obj1 valueForKey:@"orderNum"] integerValue] > [[obj2 valueForKey:@"orderNum"] integerValue]) {
            return (NSComparisonResult)NSOrderedDescending;
        }
        if ([[obj1 valueForKey:@"orderNum"] integerValue] < [[obj2 valueForKey:@"orderNum"] integerValue]) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        return (NSComparisonResult)NSOrderedSame;
    }];

and add the sorted data back to RLMArray

    [myLog.myRLMArray removeAllObjects];
    [myLog.myRLMArray addObjects:tempWelLogCopy];
Teja Nandamuri
  • 11,045
  • 6
  • 57
  • 109