Baffled by NSMutableArray sortUsingDescriptors: exception

时光怂恿深爱的人放手 提交于 2019-12-25 07:25:09

问题


The following method:

- (NSMutableArray*) timeSortedBegins {
    NSMutableArray* begins = [self.spans valueForKey: @"begin"];
    NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey: @"cycleOffsetObject" ascending: YES];
    [begins sortUsingDescriptors: @[sort]];
    return begins;
}

throws this runtime exception:

2014-03-21 14:41:32.482 myValve[1741:60b] -[__NSArrayI sortUsingDescriptors:]: unrecognized selector sent to instance 0x16d7bc20
2014-03-21 14:41:32.484 myValve[1741:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI sortUsingDescriptors:]: unrecognized selector sent to instance 0x16d7bc20'

I have used breakpoints to convince myself that the begins array is indeed full of (two in this case) WEAnchor* objects. And that object implements the following two methods:

- (NSTimeInterval) cycleOffset {
    return self.offset + (self.datum ? self.datum.cycleOffset : 0.0);
}

- (NSNumber*) cycleOffsetObject {
    return [NSNumber numberWithDouble: self.cycleOffset];
}

To be honest, I only added the cycleOffsetObject wrapper method, because I thought maybe it couldn't work with non object values, I was using initWithKey: @"cycleOffset" before that. I have not declared these in the header file as a property, they're just accessor methods, not state. Is that the problem? If it is, how do you sort by the return value of a given selector? Or is it something head smackingly obvious that I'm just missing?


回答1:


As @dtrotzjr says, it sounds like your array is an immutable, not a mutable array.

You can either use mutableCopy to create a mutable copy and then sort that copy, or use the NSArray method sortedArrayUsingDescriptors: (which operates on an immutable array, and returns a sorted version of the contents as a second immutable array.)

To use mutableCopy, your code might look like this:

- (NSMutableArray*) timeSortedBegins {
    NSMutableArray* begins = [[self.spans valueForKey: @"begin"] mutableCopy];
    NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey: @"cycleOffsetObject" ascending: YES];
    [begins sortUsingDescriptors: @[sort]];
    return begins;
}



回答2:


Check that [self.spans valueForKey: @"begin"] is actually an NSMutableArray before casting it. The error message indicates that the pointer is actually an NSArray



来源:https://stackoverflow.com/questions/22570144/baffled-by-nsmutablearray-sortusingdescriptors-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!