Objective-C的分类问题
-
25-09-2019 - |
题
我已经创建的自定义通过创建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:
以后每次通话?
解决方案
这是用于静态关键字的作业。如果你这样做:
static NSDictionary *pointDictionary = nil
if (pointDictionary==nil) {
NSString *pointPath = [[NSBundle mainBundle] pathForResource:@"pointvalues" ofType:@"plist"];
pointDictionary = [[NSDictionary alloc] initWithContentsOfFile:pointPath];
}
pointDictionary
将是您的应用的寿命持久。
其他一种优化是通过使用该对每部话建立分数的缓存:
[dict setObject:[NSNumber numberWithInt:[word calculateWordValue:word]] forKey:word];
然后使用keysSortedByValueUsingSelector:
方法提取的单词列表(注意选择chould被比较:,由于被比较的对象是NSNumbers)。
最后,关于您的方法字参数是多余的。使用自代替:
-(int)calculateWordValue {
...
for (int index = 0; index < [self length]; index++)
{
char currentChar = [self characterAtIndex:index];
...
}
...
}
其他提示
变更sortByPoint:(NSString *) otherString
方法采取字典作为参数,并把它传递您的预先创建的字典。
sortByPoint:(NSString *)otherString withDictionary:(NSDictionary *)pointDictionary
编辑:会不会因为在sortedArrayWithSelector使用的工作。道歉。相反,你可能会更好为您点字典作为一个单独然后您可以获取每次您的排序功能的运行参考创建的包装类。
在calculateWordValue
:
NSDictionary *pointDictionary = [[DictWrapper sharedInstance] dictionary];
DictWrapper
有一个NSDictionary作为一个属性,一个类的方法sharedInstance
(返回单身,你必须设置字典和你做你第一次分拣之前预先初始化。
不隶属于 StackOverflow