あなたの質問への答えは、あなたの(与えられた)質問のこの部分でした。「私は、どのパターンにいくつの単語があるか知っています。私は辞書の配列を使用します。辞書を使用して、既知のパターンとカウントであるキー値のペアを格納します。そして、それらのKVPレコードを格納するために配列を使います。次回パターンを検出したら、そのレコード(ディクショナリ)の配列を検索し、見つかった場合はカウントをインクリメントします。ない場合は、新しいレコードを作成し、1
追加のサンプルコードに回数を設定します。
#define kPattern @"Pattern"
#define kPatternCount @"PatternCount"
-(NSMutableDictionary *)createANewDictionaryRecord:(NSString *) newPattern
{
int count = 1;
NSMutableDictionary *myDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
newPattern, kPattern,
[NSString stringWithFormat:@"%i",count], kPatternCount,
nil];
return myDictionary;
}
-(void)addANewPatternToArray:(NSMutableDictionary *)newDictionary
{
// NSMutableArray *myArrayOfDictionary = [[NSMutableArray alloc]init]; // you need to define it somewhere else and use property etc.
[self.myArrayOfDictionary addObject:newDictionary]; //or [self.myArrayOfDictionary addObject:newDictionary]; if you follow the recommendation above.
}
-(BOOL)existingPatternLookup:(NSString *)pattern
{
for (NSMutableDictionary *obj in self.myArrayOfDictionary)
{
if ([[obj objectForKey:kPattern] isEqual:pattern])
{
int count = [[obj objectForKey:kPatternCount] intValue] + 1;
[obj setValue:[NSString stringWithFormat:@"%i",count] forKey:kPatternCount];
return YES;
}
}
[self.myArrayOfDictionary addObject:[self createANewDictionaryRecord:pattern]];
return NO;
}
-(void)testData
{
NSMutableDictionary *newDict = [self createANewDictionaryRecord:@"mmm"];
[self addANewPatternToArray:newDict];
}
-(void) printArray
{
for (NSMutableDictionary * obj in self.myArrayOfDictionary)
{
NSLog(@"mydictionary: %@", obj);
}
}
- (IBAction)buttonPressed:(id)sender
{
if ([self existingPatternLookup:@"abc"])
{
[self printArray];
} else
{
[self printArray];
}
}
ありがとうございます。これがどのように実装されるかのスニペットがありますか?私はこのアプローチが好きですが、構文に苦しんでいます。 – user1278974
完全なサンプルコードを追加しました。 btw:コードは決して最適化されません! – user523234
編集すると、既存のパターンルックアップのforループの外にaddOjectが移動します。 – user523234