クラスの新しいカテゴリを作成して、カスタムの並べ替えを作成しましたNSString
。以下は私のコードです。
@implementation NSString (Support)
- (NSComparisonResult)sortByPoint:(NSString *)otherString {
int first = [self calculateWordValue:self];
int second = [self calculateWordValue:otherString];
if (first > second) {
return NSOrderedAscending;
}
else if (first < second) {
return NSOrderedDescending;
}
return NSOrderedSame;
}
- (int)calculateWordValue:(NSString *)word {
int totalValue = 0;
NSString *pointPath = [[NSBundle mainBundle] pathForResource:@"pointvalues"ofType:@"plist"];
NSDictionary *pointDictionary = [[NSDictionary alloc] initWithContentsOfFile:pointPath];
for (int index = 0; index < [word length]; index++) {
char currentChar = [word characterAtIndex:index];
NSString *individual = [[NSString alloc] initWithFormat:@"%c",currentChar];
individual = [individual uppercaseString];
NSArray *numbersForKey = [pointDictionary objectForKey:individual];
NSNumber *num = [numbersForKey objectAtIndex:0];
totalValue += [num intValue];
// cleanup
individual = nil;
numbersForKey = nil;
num = nil;
}
return totalValue;
}
@end
私の質問は、plistに基づいてアルファベットの各文字に関連付けられたポイント値を決定するためにポイントディクショナリを作成するかどうかです。次に、View Controllerで、
NSArray *sorted = [words sortedArrayUsingSelector:@selector(sortByPoint:)];
単語のテーブルをポイント値で並べ替えます。ただし、メソッドが呼び出されるたびに新しいディクショナリを作成することは、-sortByPoint:
非常に非効率的です。事前にpointDictionaryを作成し、それを以降の呼び出しごとに使用する方法はあり-calculateWordValue:
ますか?