字符串如
"4 Miles 400 stones"
"2 Miles 10 stones"
"6 Miles 2 Stones"
NsMutableArray
中字典的键值,我试图按英里数然后按石头对它们进行排序。
常规sortUsingDescriptor
:
[list sortUsingDescriptors:[NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:@"systems"升序:YES], nil]];
或NSNumericSearch
:
NSMutableArray *newList;
NSArray *result = [list sortedArrayUsingFunction:&sort context:@"systems"];
newList= [[NSMutableArray alloc] initWithArray:result];
NSInteger sort(id a, id b, void* p) {
return [[a valueForKey:(__bridge NSString*)p]
compare:[b valueForKey:(__bridge NSString*)p]
options:NSNumericSearch];
}
不工作。
我是否必须解析字符串并获取数字然后对其进行排序?或者有更简单的方法来对此进行排序吗?
最佳答案
这是最好的、面向对象的方法。
首先。创建一个类。我们将其命名为 MyObject
:
@interface MyObject : NSObject
@property(nonatomic, assign) NSUInteger miles;
@property(nonatomic, assign) NSUInteger stones;
+ (MyObject *)objectWithString:(NSString *)string;
@end
如您所见,它有一个 objectWithString
,我们将使用它来使用字符串中的信息创建对象,例如:“4 Miles 400stones”
。
@implementation MyObject
+ (MyObject *)objectWithString:(NSString *)string
{
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[0-9]+?(?= Miles | stones)" options:0 error:nil];
NSArray *matches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
MyObject *myObject = [[MyObject alloc] init];
myObject.miles = [[string substringWithRange:((NSTextCheckingResult *)matches[0]).range] integerValue];
myObject.stones = [[string substringWithRange:((NSTextCheckingResult *)matches[1]).range] integerValue];
return myObject;
}
- (NSString *)description
{
return [NSString stringWithFormat:@"%d miles, %d stones", self.miles, self.stones];
}
@end
然后,我们将使用 NSSortDescriptor
对我们的数组进行排序:
MyObject *myObject1 = [MyObject objectWithString:@"4 Miles 400 stones"];
MyObject *myObject2 = [MyObject objectWithString:@"2 Miles 10 stones"];
MyObject *myObject3 = [MyObject objectWithString:@"6 Miles 2 stones"];
NSArray *array = @[myObject1, myObject2, myObject3];
NSSortDescriptor *miles = [[NSSortDescriptor alloc] initWithKey:@"miles" ascending:YES];
NSSortDescriptor *stones = [[NSSortDescriptor alloc] initWithKey:@"stones" ascending:YES];
NSArray *sortDescriptors = @[miles, stones];
NSArray *sortedArray = [array sortedArrayUsingDescriptors:sortDescriptors];
NSLog(@"Sorted: %@", sortedArray);
输出:
2014-03-05 19:51:54.233 demo[12267:70b] Sorted: (
"2 miles, 10 stones",
"4 miles, 400 stones",
"6 miles, 2 stones" )
它就像一个魅力,我的 friend !
关于ios - 排序字符串包含数字,NSMutableArray 与字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22205011/