我通过为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 确定与字母表中每个字符相关联的点值。然后在我的视图控制器中,我调用
NSArray *sorted = [words sortedArrayUsingSelector:@selector(sortByPoint:)];
按点值对我的单词表进行排序。但是,每次-sortByPoint:
调用该方法时都创建一个新字典是非常低效的。有没有办法预先创建 pointDictionary 并将其用于 中的每个后续调用-calculateWordValue:
?