我正在运行此代码以创建包含调用者名称的图像,并将其设置为特定联系人,但在运行时,我收到内存警告并且崩溃...
-(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];
提前致谢。
答案 0 :(得分:2)
如果您正在迭代一个大型数组并获得内存警告,那么您可能正在使用在退出for
循环之后才会释放的资源。 (或者在这种情况下,根本没有发布,因为你的应用程序崩溃了。)
您希望使用
将代码包装在循环中for (int i=0; i<max; i++) {
@autoreleasepool {
}
}
答案 1 :(得分:0)
看起来你的内存不足,同时保留了很多无法释放的对象,比如addressBook
内容,而且你似乎还有一个名为{addressBook
的完整副本array
1}}。
所以,
addressBook
的副本吗?试着摆脱它。接下来,您可以尝试使用Instruments分析您的分配,并查看占用大部分内存的内容。