-3

我正在运行此代码以创建包含呼叫者姓名的图像,并将其设置为特定联系人,但是在运行时,我收到 Received memory 警告并且它崩溃了...

-(void)RunActionInBlack{


//black bg - white text

ABAddressBookRef addressBook;
CFErrorRef error = NULL;

addressBook = ABAddressBookCreate();

CFArrayRef array=ABAddressBookCopyArrayOfAllPeople(addressBook);

ABRecordRef person;
int len=CFArrayGetCount(array);

for (int i = 0; i<len; i++){
    person = CFArrayGetValueAtIndex(array, i);
     details.text = [NSString stringWithFormat:@"Done. %d of %d contacts", i+1,len];
    [act stopAnimating];
    NSString *firstName = (NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
    NSString *lastName = (NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);

    if (firstName == NULL) {
        firstName = @"";
    }
    if (lastName == NULL ) {
        lastName = @"";
    }

    UIImage *im = [self addText:[UIImage imageNamed:@"black.png"] andText:[NSString stringWithFormat:@"%@ %@",firstName, lastName]];
    NSData *dataRef = UIImagePNGRepresentation(im);

    ABPersonSetImageData(person, (CFDataRef)dataRef, &error);


    [lastName release];
    [firstName release];
    [dataRef release];
    CFRelease(dataRef);
    [im release];
}
ABAddressBookSave(addressBook, &error);
CFRelease(array);
CFRelease(addressBook);
}

创建文本:

-(UIImage *)addText:(UIImage *)img andText:(NSString*)txt{

UIImageView *imView =[[UIImageView alloc] initWithImage:img ];
UIView *tempView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, img.size.width, img.size.height)];
[tempView addSubview:imView];

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, -100, img.size.width, img.size.height)];
[label setText:txt];
[label setFont:[UIFont boldSystemFontOfSize:160]];
[label setTextColor:[UIColor whiteColor]];
[label setTextAlignment:UITextAlignmentCenter];
[label setBackgroundColor:[UIColor clearColor]];
[label setNumberOfLines:10];
[tempView addSubview:label];

UIGraphicsBeginImageContext(tempView.bounds.size);
[tempView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[label release];
[tempView release];
[imView release];
return finalImage;
}

我没有任何内存泄漏或什么的...

我正在运行这些方法,例如:[self performSelectorInBackground:@selector(RunActionInWhite) withObject:nil];

提前致谢。

4

2 回答 2

2

如果您正在遍历一个大型数组并收到内存警告,则您可能正在使用直到退出for循环后才被释放的资源。(或者在这种情况下,根本没有发布,因为您的应用程序崩溃了。)

您可能希望将代码包装在循环中

for (int i=0; i<max; i++) {
    @autoreleasepool {

    }
}
于 2013-02-16T20:42:13.927 回答
0

似乎您的内存不足,同时保留了许多无法释放的对象,例如addressBook内容,而且您似乎拥有 call 的完整addressBook副本array

所以,

  • 你真的需要那个副本addressBook吗?尝试摆脱它。
  • 将迭代分成更小的部分,在每块几十条记录之后保存地址簿,这应该会释放一些内部使用的资源。

接下来,您可以尝试使用 Instruments 分析您的分配,看看是什么占用了大部分内存。

于 2013-02-16T20:56:46.913 回答