http://i46.tinypic.com/2nquzag.png
我有一个应用程序可以在很长的计算过程中创建和释放数百万个 NSNumber。我将@autoreleasepools 与创建和处理这些对象的各种循环一起使用。正如您在仪器屏幕上看到的那样,我只有 10656 个活动 CFNumber,但此时应用程序由于无法为更多对象分配内存而崩溃。有超过 5700 万个 CFNumber 处于“临时”状态。这是否意味着他们被释放了?为什么 malloc 还不使用这些内存位置?
我已经包含了我正在使用的代码的模型。运行 testProbabilities 方法,它将每 10000 次迭代计数一次。在分配错误之前,我使用此代码进行了多达 790000 次迭代。然而 Instruments 对我来说看起来不错。
@implementation MMTest
NSMutableSet *predictedSet;
-(NSMutableArray *)calculateCDF {
//// NORMALIZE PROBABILITIES ////
float probabilitySum = 0;
float runningCDFTotal = 0;
float normaledProbability = 0;
@autoreleasepool {
NSMutableArray *CDF = [[NSMutableArray alloc] init];
probabilitySum = 4.5; ////This is just a placholder for additive iteration of an array which creates this sum.
//// CREATE CDF ////
int x;
for (x=0; x<50; x++) {
normaledProbability = .2/probabilitySum;////This is placeholder for calculation on same array as above.
runningCDFTotal += normaledProbability;
[CDF addObject:[NSNumber numberWithFloat:runningCDFTotal]];
}
return CDF;
}
}
-(NSMutableSet *)generateNumbers {
@autoreleasepool {
int x;
double r = 0;
if (!predictedSet) {
predictedSet = [[NSMutableSet alloc] init];
}
else {
[predictedSet removeAllObjects];
}
for (x=0; x<5;) {
r = arc4random_uniform(1000)/1000;////I'm actually using SFMT here instead.
int num = 0;
__weak id CDF = [self calculateCDF];
if (r <= [[CDF objectAtIndex:[CDF count]-1] floatValue]) {
for (NSNumber *cdf in CDF) {
if (r <= [cdf floatValue]) {
num = [CDF indexOfObject:cdf]+1;
[predictedSet addObject:[NSNumber numberWithInt:num]];
x++;
break;
}
}
}
}
return predictedSet;
}
}
-(void)testProbability {
int x = 0;
BOOL nextSetFound = NO;
NSSet *nextSet = [[NSSet alloc] initWithObjects:
[NSNumber numberWithInt:1],
[NSNumber numberWithInt:2],
[NSNumber numberWithInt:3],
[NSNumber numberWithInt:4],
[NSNumber numberWithInt:5],
nil];
while (nextSetFound == NO) {
@autoreleasepool {
__weak id newSet = [self generateNumbers];
x++;
if ([nextSet isSubsetOfSet:newSet]) {
nextSetFound = YES;
NSLog(@"%@", newSet);
}
if (fmod (x,10000) == 0) {
NSLog(@"%i", x);
}
}
}
NSLog(@"%i", x);
}
@end