我在我的 x-code 项目中创建了一个类别,如下所示:
+ (NSDictionary *)anagramMap {
static NSDictionary *anagramMap;
if (anagramMap != nil)
return anagramMap;
// this file is present on Mac OS and other unix variants
NSString *allWords = [NSString stringWithContentsOfFile:@"/usr/share/dict/words"
encoding:NSUTF8StringEncoding
error:NULL];
NSMutableDictionary *map = [NSMutableDictionary dictionary];
@autoreleasepool {
[allWords enumerateLinesUsingBlock:^(NSString *word, BOOL *stop) {
NSString *key = [word anagramKey];
if (key == nil)
return;
NSMutableArray *keyWords = [map objectForKey:key];
if (keyWords == nil) {
keyWords = [NSMutableArray array];
[map setObject:keyWords forKey:key];
}
[keyWords addObject:word];
}];
}
anagramMap = map;
return anagramMap;}
- (NSString *)anagramKey {
NSString *lowercaseWord = [self lowercaseString];
// make sure to take the length *after* lowercase. it might change!
NSUInteger length = [lowercaseWord length];
unichar sortedWord[length];
[lowercaseWord getCharacters:sortedWord range:(NSRange){0, length}];
qsort_b(sortedWord, length, sizeof(unichar), ^int(const void *a, const void *b) {
unichar c1 = *(const unichar *)a;
unichar c2 = *(const unichar *)b;
if (c1 > c2)
return -1;
if (c1 < c2)
return 1;
return 0;
});
return [NSString stringWithCharacters:sortedWord length:length];}
基本上,这段代码循环遍历 Mac OSx 字典并将其转换为 NSDictionary,其中键是按字母顺序排序的单词,对象是该单词所有字谜的数组。
我想知道的是,如何调用此方法,例如在实现文件的 viewDidLoad 部分中,该部分将分配一个 NSDictionary(或可变)这个创建的排序键和对象数组的字典?基本上在伪代码中我做了类似的事情:
NSMutableArray *englishDictionary = [[NSMutableArray alloc] init]; EnglishDictionary = [NSMutableArray anagramMapScrabble]; //应该意味着现在englishDictionary已经变成了NSDictionary,其中key = sorted word,object是那个sorted word的英文字谜数组
我想我必须在方法中添加一些额外的代码,但我不确定。我们欢迎所有的建议!