我有一個UIView必須顯示一些信息。由於這個視圖非常複雜,並且繪圖需要大量的時間,所以我將它移到後臺線程以避免阻塞主線程。繪圖完成後,我將發回主線程以設置ImageView。繪製到背景線程上下文
以下代碼爲我繪製圖形,但我收到一些偶爾的崩潰。在[view release];
通常的Xcode點,並說Thread 6: Program received signal: EXC_BAD_ACCESS
NSManagedObjectID *objectID = [self.managedObject objectID];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
dispatch_async(queue,^{
NSManagedObjectContext *backgroundContext = [[NSManagedObjectContext alloc] init];
[backgroundContext setPersistentStoreCoordinator:[[self.managedObject managedObjectContext] persistentStoreCoordinator]];
NSManagedObject *mo = [backgroundContext objectWithID:objectID];
CGImageRef resultImage;
CGContextRef context;
void *bitmapData;
CGRect frame = self.frame;
frame.origin = CGPointZero;
CGColorSpaceRef colorSpace;
CGSize canvasSize;
int bitmapByteCount;
int bitmapBytesPerRow;
canvasSize = frame.size;
CGFloat scale = [UIScreen instancesRespondToSelector:@selector(scale)] ? [[UIScreen mainScreen] scale] : 1.0f;
canvasSize.width *= scale;
canvasSize.height *= scale;
bitmapBytesPerRow = (canvasSize.width * 4);
bitmapByteCount = (bitmapBytesPerRow * canvasSize.height);
//Create the color space
colorSpace = CGColorSpaceCreateDeviceRGB();
bitmapData = malloc(bitmapByteCount);
//Check the the buffer is alloc'd
if(bitmapData == NULL){
DLog(@"Buffer could not be alloc'd");
}
//Create the context
context = CGBitmapContextCreate(bitmapData, canvasSize.width, canvasSize.height, 8, bitmapBytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast);
CGContextClearRect(context, CGRectMake(0, 0, canvasSize.width, canvasSize.height));
// Setup transformation
CGContextSetInterpolationQuality(context, kCGInterpolationNone);
CGContextTranslateCTM(context, 0.0f, canvasSize.height);
CGContextScaleCTM(context, scale, -scale);
UIView *view = [[UIView alloc] initWithFrame:frame];
[view setBackgroundColor:[UIColor clearColor]];
UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(137, 5, 255, 30)];
[nameLabel setFont:[UIFont fontWithName:@"Arial" size:22.0f]];
[nameLabel setText:[mo valueForKey:@"name"]];
[nameLabel setTextAlignment:UITextAlignmentRight];
[view addSubview:nameLabel];
[nameLabel release];
nameLabel = nil;
... Creating 20 or so label/imageviews all use 'mo' for data access to the NSManagedObject.
[view.layer renderInContext:context];
[view release];
view = nil;
//Get the result image
resultImage = CGBitmapContextCreateImage(context);
UIImage *viewImage = [UIImage imageWithCGImage:resultImage scale:0.0 orientation:UIImageOrientationUp];
dispatch_async(dispatch_get_main_queue(),^ {
[dataImageView setImage:viewImage];
});
//Cleanup
free(bitmapData);
CGColorSpaceRelease(colorSpace);
CGImageRelease(resultImage);
CGContextRelease(context);
});
希望你們能幫助我,因爲我不能讓這頭或尾。我曾嘗試與NSZombieEnabled是一些次導致以下錯誤控制檯-[UILabel hash]: message sent to deallocated instance 0x22841c00
感謝您的答案,但一開始我嘗試沒有nameLabel =零;聲明和結果是一樣的,偶爾發生崩潰:( – mbogh
)您不會刪除內存區域,只有指向內存區域的指針。該視圖將一直存儲在內存中,直到所有引用都被釋放爲止。 –