由于我在这里收到了很多帮助,所以我得到了一个算法来检查一个大约15000个8个字母的单词的列表,对于任何一个部分的字谜,与一个大约50000个单词的列表(所以我假设总共有1亿800万次迭代)。对于每个比较,我调用这个方法一次(7亿5000万次)。我得到了下面的错误,总是在第119次迭代到1350次迭代中的某个地方应该有:

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

我已经将内存问题缩小为大量分配的CFStand(不可变)。你知道我能做些什么来解决这个问题吗?我正在使用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--;
    }
}

最佳答案

问题似乎是很多自动释放的对象填满了等待释放的内存。所以一个解决方案是添加您自己的自动释放池作用域来收集自动释放的对象并尽快释放它们。
我建议你这样做:

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

现在,@autoreleasepool { .. }中所有自动释放的对象都将在外部循环的每次迭代中被释放。
正如您所看到的,arc可以避免您考虑大多数引用计数和内存管理问题,但是当使用直接或间接创建自动释放对象的方法时,对象仍然可以与arc一起出现在自动释放池中。
另一个我并不推荐的解决方案是尽量避免使用将使用autorelease的方法。然后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;
}

关于objective-c - 运行数百万次循环时“无法分配区域” malloc错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13396560/

10-10 05:04