4

多亏了我在这里收到的很多帮助,我得到了一个算法来检查任何部分字谜的大约 15,000 个 8 字母单词的列表,对照大约 50,000 个总单词的列表(所以我想总共1.08 亿次迭代)。每次比较我都会调用一次这个方法(所以 7.5 亿次)。我收到以下错误,总是在第 119 次迭代到 1,350 的中间某个地方应该有:

AnagramFINAL(2960,0xac8c7a28) malloc: *** mmap(size=2097152) failed (error code=12)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug

我已将内存问题缩小为大量分配的 CFStrings(不可变)。知道我能做些什么来解决这个问题吗?我正在使用 ARC 和@autoreleasepool,不知道我还能做什么,似乎有些东西没有在应该发布的时候发布。

AnagramDetector.h

#import <Foundation/Foundation.h>

@interface AnagramDetector : NSObject {

        NSDictionary *allEightLetterWords;
NSDictionary *allWords;

    NSFileManager *fileManager;
    NSArray *paths;
    NSString *documentsDirectory;
    NSString *filePath;
}

- (BOOL) does: (NSString *) longWord contain: (NSString *) shortWord;
- (NSDictionary *) setupAllWordList;
- (NSDictionary *) setupEightLetterWordList;
- (void) saveDictionary: (NSMutableDictionary *)currentArray;

@end

AnagramDetector.m

@implementation AnagramDetector

- (id) init {
    self = [super init];
    if (self) {
        fileManager = [NSFileManager defaultManager];
        paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        documentsDirectory = [paths objectAtIndex:0];
    }
    return self;
}

- (BOOL) does: (NSString *) longWord contain: (NSString *) shortWord {
    @autoreleasepool {
          NSMutableString *longerWord = [longWord mutableCopy];
          for (int i = 0; i < [shortWord length]; i++) {
              NSString *letter = [shortWord substringWithRange: NSMakeRange(i, 1)];
              NSRange letterRange = [longerWord rangeOfString: letter];
              if (letterRange.location != NSNotFound) {
                  [longerWord deleteCharactersInRange: letterRange];
              } else {
                  return NO;
              }
          }
        return YES;
    }
}

- (NSDictionary *) setupAllWordList {

    @autoreleasepool {
        NSString *fileWithAllWords = [[NSBundle mainBundle] pathForResource:@"AllDefinedWords" ofType:@"plist"];
        allWords = [[NSDictionary alloc] initWithContentsOfFile: fileWithAllWords];
        NSLog(@"Total number of words: %d.", [allWords count]);
    }
    return allWords;
}


- (NSDictionary *) setupEightLetterWordList {

    @autoreleasepool {
        NSString *fileWithEightWords = [[NSBundle mainBundle] pathForResource:@"AllDefinedEights" ofType:@"plist"];
        allEightLetterWords = [[NSDictionary alloc] initWithContentsOfFile: fileWithEightWords];
        NSLog(@"Total number of words: %d.", [allEightLetterWords count]);
    }
    return allEightLetterWords;
}

- (void) saveDictionary: (NSMutableDictionary *)currentArray {

    @autoreleasepool {
        filePath = [documentsDirectory stringByAppendingPathComponent: @"A.plist"];
        [fileManager createFileAtPath:filePath contents: nil attributes: nil];
        [currentArray writeToFile: filePath atomically:YES];
        [currentArray removeAllObjects];
    }
}

@end

启动时运行的代码(现在在 AppDelegate 中,因为没有 VC):

@autoreleasepool {

    AnagramDetector *detector = [[AnagramDetector alloc] init];

    NSDictionary *allWords   = [[NSDictionary alloc] initWithDictionary:[detector setupAllWordList]];
    NSDictionary *eightWords = [[NSDictionary alloc] initWithDictionary:[detector setupEightLetterWordList]];

    int remaining = [eightWords count];

    for (NSString *currentEightWord in eightWords) {
        if (remaining % 10 == 0) NSLog(@"%d ::: REMAINING :::", remaining);
        for (NSString *currentAllWord in allWords) {
            if ([detector does: [eightWords objectForKey: currentEightWord] contain: [allWords objectForKey: currentAllWord]]) {
                // NSLog(@"%@ ::: CONTAINS ::: %@", [eightWords objectForKey: currentEightWord], [allWords objectForKey: currentAllWord]);
            }
        }
        remaining--;
    }
}

仪器

4

1 回答 1

5

问题似乎是很多自动释放的对象填满了等待释放的内存。所以一个解决方案是添加你自己的自动释放池范围来收集自动释放的对象并更快地释放它们。

我建议你做这样的事情:

for (NSString *currentEightLetterWord in [eightLetterWordsDictionary allKeys]) {
    @autoreleasepool { 
        for (NSString *currentWord in [allWordsDictionary allKeys]) {
        }
    }
}

现在,内部所有自动释放的对象@autoreleasepool { .. }都将在外部循环的每次迭代中释放。

正如您所看到的,ARC 可能使您不必考虑大多数引用计数和内存管理问题,但是当使用直接或间接创建自动释放对象的方法时,对象仍然可以最终在 ARC 的自动释放池中。

我不真正推荐的另一种解决方案是尽量避免使用将使用自动释放的方法。然后does:contain:可以尴尬地重写为这样的东西:

- (BOOL) does: (NSString* ) longWord contain: (NSString *) shortWord {
    NSMutableString *haystack = [longWord mutableCopy];
    NSMutableString *needle = [shortWord mutableCopy];
    while([haystack length] > 0 && [needle length] > 0) {
        NSMutableCharacterSet *set = [[NSMutableCharacterSet alloc] init];
        [set addCharactersInRange:NSMakeRange([needle characterAtIndex:0], 1)];
        if ([haystack rangeOfCharacterFromSet:set].location == NSNotFound) return NO;
        haystack = [haystack mutableCopy];
        [haystack deleteCharactersInRange:NSMakeRange(0, [haystack rangeOfCharacterFromSet: set].location)];
        needle = [needle mutableCopy];
        [needle deleteCharactersInRange:NSMakeRange(0, 1)];
    }
    return YES;
}
于 2012-11-15T14:47:38.277 回答