質問

私は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のに基づいて、アルファベットの各文字に関連付けられたポイント値を決定するためのポイント辞書を作成するかどうかです。その後、私のビューコントローラでは、Iコール

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:メソッドを使用し(注比較されているオブジェクトがNSNumbersあるのでセレクタ:,比較するchould)。

最後に、あなたの方法上のワード引数は冗長です。代わりに自己を使用します:

-(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を(シングルトンを返すように。あなたはその辞書を設定すると、あなたが最初の並べ替えを行う前に、それを事前に初期化する必要があります。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top