0

クラスの新しいカテゴリを作成して、カスタムの並べ替えを作成しました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:ますか?

4

2 に答える 2

4

これはstaticキーワードの仕事です。これを行う場合:

static NSDictionary *pointDictionary = nil
if (pointDictionary==nil) {
    NSString *pointPath = [[NSBundle mainBundle] pathForResource:@"pointvalues" ofType:@"plist"];
    pointDictionary = [[NSDictionary alloc] initWithContentsOfFile:pointPath];
}

pointDictionaryアプリの存続期間中は永続的です。

もう1つの最適化は、各単語に対してこれを使用してスコアのキャッシュを構築することです。

[dict setObject:[NSNumber numberWithInt:[word calculateWordValue:word]] forKey:word];

次に、このkeysSortedByValueUsingSelector:メソッドを使用して単語のリストを抽出します(比較されるオブジェクトはNSNumbersであるため、セレクターはcompare:であることに注意してください)。

最後に、メソッドの引数という単語は冗長です。代わりにselfを使用してください:

-(int)calculateWordValue {
    ...

    for (int index = 0; index < [self length]; index++)
    {
        char currentChar = [self characterAtIndex:index];
        ...
    }
   ...
}
于 2010-11-17T20:07:00.907 に答える
0

ディクショナリをパラメータとして受け取るようにメソッドを変更sortByPoint:(NSString *) otherStringし、事前に作成したディクショナリを渡します。

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

編集:sortedArrayWithSelectorで使用されているため、機能しません。謝罪。代わりに、ポイントディクショナリのラッパークラスをシングルトンとして作成し、ソート関数を実行するたびに参照を取得する方がよい場合があります。

calculateWordValue

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

DictWrapperプロパティとしてNSDictionaryがあり、クラスメソッドsharedInstance(シングルトンを返すため。最初に並べ替える前に、そのディクショナリを設定して事前に初期化する必要があります。

于 2010-11-17T19:41:58.683 に答える