Objective-C类别问题

时间:2010-11-17 19:32:58

标签: objective-c sorting objective-c-category

我通过为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:中的每个后续调用?

2 个答案:

答案 0 :(得分:4)

这是static关键字的作业。如果你这样做:

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:方法提取单词列表(注意选择器可以比较:,因为被比较的对象是NSNumbers)。

最后,关于你的方法的单词参数是多余的。请改用self:

-(int)calculateWordValue {
    ...

    for (int index = 0; index < [self length]; index++)
    {
        char currentChar = [self characterAtIndex:index];
        ...
    }
   ...
}

答案 1 :(得分:0)

更改sortByPoint:(NSString *) otherString方法,将字典作为参数,并将其传递给预先创建的字典。

sortByPoint:(NSString *)otherString withDictionary:(NSDictionary *)pointDictionary

编辑:因为在sortedArrayWithSelector中的使用而无法工作。道歉。相反,您可能最好为点字典创建一个包装类作为单例,然后在每次运行排序函数时获取引用。

calculateWordValue

NSDictionary *pointDictionary = [[DictWrapper sharedInstance] dictionary];

DictWrapper有一个NSDictionary作为属性,一个类方法sharedInstance(返回单例。你必须设置该字典并在你第一次排序之前预先初始化它。