這裏是如何做到這一點的最好,面向對象的方式。
首先。創建一個班級。讓我們把它叫做MyObject
:
@interface MyObject : NSObject
@property(nonatomic, assign) NSUInteger miles;
@property(nonatomic, assign) NSUInteger stones;
+ (MyObject *)objectWithString:(NSString *)string;
@end
正如你所看到的,它有一個objectWithString
,我們將使用在像字符串,創建利用信息的對象:"4 Miles 400 stones"
。
@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")
它的工作原理就像一個魅力我的朋友!
我可能會創建一個自定義類,它們將這些值保存爲數字類型,並簡單地覆蓋用這種格式打印的「description」方法,而不是試圖將數據作爲字符串進行存儲和排序。 – nhgrif
什麼是關鍵,什麼值? – vikingosegundo