gpt4 book ai didi

iphone - 内存高效集合类

转载 作者:搜寻专家 更新时间:2023-10-30 19:51:34 24 4
gpt4 key购买 nike

我正在我的 iPhone 应用程序中构建一个字典数组(称为键)来保存 TableView 的部分名称和行数。

代码如下所示:

[self.results removeAllObjects];
[self.keys removeAllObjects];

NSUInteger i,j = 0;
NSString *key = [NSString string];
NSString *prevKey = [NSString string];

if ([self.allResults count] > 0)
{
prevKey = [NSString stringWithString:[[[self.allResults objectAtIndex:0] valueForKey:@"name"] substringToIndex:1]];

for (NSDictionary *theDict in self.allResults)
{
key = [NSString stringWithString:[[theDict valueForKey:@"name"] substringToIndex:1]];

if (![key isEqualToString:prevKey])
{
NSDictionary *newDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:i],@"count",
prevKey,@"section",
[NSNumber numberWithInt:j],
@"total",nil];

[self.keys addObject:newDictionary];
prevKey = [NSString stringWithString:key];
i = 1;
}
else
{
i++;
}
j++;

}

NSDictionary *newDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:i],@"count",
prevKey,@"section",
[NSNumber numberWithInt:j],
@"total",nil];

[self.keys addObject:newDictionary];

}

[self.tableview reloadData];

代码第一次运行时运行良好,但有时我必须重建整个表,所以我重做这段代码,在模拟器上运行良好,但在我的设备上,当我执行 reloadData 行时程序崩溃:

malloc: *** mmap(size=3772944384) failed (error code=12)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
malloc: *** mmap(size=3772944384) failed (error code=12)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
Program received signal: “EXC_BAD_ACCESS”.

如果我删除 reloadData 行,代码将在设备上运行。

我想知道这是否与我构建键数组的方式有关(即使用自动释放的字符串和字典)。

最佳答案

错误消息为您提供了分配失败的非常明确的原因:

malloc: *** mmap(size=3772944384) failed (error code=12)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
malloc: *** mmap(size=3772944384) failed (error code=12)
*** error: can't allocate region

具体大小为3,772,944,384;差不多4GB。 IE。你要求 malloc() 分配一些东西,导致 malloc 认为它需要内存映射 (mmap) 将近 4GB 的地址空间!

现在,如果您的输入字符串真的非常庞大,那么您的代码将像 davydotcom 所说的那样膨胀自动释放池,但它们必须非常非常才能导致这种情况发生。如果它有那么大,那么您最终会在表中得到数万行还是数十万行?如果是这样,请不要那样做——这对用户来说太难了。

如错误所述,在 malloc_error 上设置断点并发布回溯。

请注意:

NSString *key = [NSString string];
NSString *prevKey = [NSString string];

是废话。

好的——再看一眼你的代码表明审查了Objective-C guideCocoa memory management指南会很有用。

在前四行代码中,你既泄漏了之前的内容又过度保留了新的self.keysself。 self.results(假设两者都是 retain 属性,因为它们应该是)。

也尝试对您的代码使用构建和分析。

关于iphone - 内存高效集合类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2930872/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com