您的问题的答案是您(给定)问题的这一部分“我会知道任何给定模式有多少个单词。”。我会使用一个字典数组。您使用字典来存储键值对:已知模式和计数。并且您使用数组来存储这些 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];
}
}