你的問題的答案是你的(給出)問題的這一部分「我會知道對於任何給定模式有多少單詞。」我會使用一個字典數組。您可以使用字典存儲鍵值對:已知模式和計數。你使用數組來存儲這些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