你的问题的答案是你的(给出)问题的这一部分“我会知道对于任何给定模式有多少单词。”我会使用一个字典数组。您可以使用字典存储键值对:已知模式和计数。你使用数组来存储这些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 2012-04-17 14:00:43
我添加了一个完整的示例代码....看看它是否有帮助。顺便说一句:代码绝不是优化的! – user523234 2012-04-17 16:19:03
编辑可将addOject移动到existingPatternLookup中for循环的外部。 – user523234 2012-04-18 23:32:31