2011-11-22 76 views
1

此代碼用於工作,但是我想Xcode的新ARC可能已經把它打死了將CGImageRef保存爲PNG文件錯誤? (ARC引起的?)

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification 
{ 
    CGDirectDisplayID displayID = CGMainDisplayID(); 
    CGImageRef image = CGDisplayCreateImage(displayID); //this is a screenshot (works fine) 
    [self savePNGImage:image path:@"~/Desktop"]; 
} 


-(void)savePNGImage:(CGImageRef)imageRef path:(NSString *)path { 
    NSURL *outURL = [[NSURL alloc] initFileURLWithPath:path]; 
    //here xcode suggests using __bridge for CFURLRef? 
    CGImageDestinationRef dr = CGImageDestinationCreateWithURL ((__bridge CFURLRef)outURL, (CFStringRef)@"public.png" , 1, NULL);  
    CGImageDestinationAddImage(dr, imageRef, NULL); 
    CGImageDestinationFinalize(dr); 
} 

此代碼返回錯誤:

ImageIO: CGImageDestinationAddImage image destination parameter is nil

我假設意味着CGImageDestinationRef是沒有被正確創建。我一直無法找到這個新的Xcode不會給出同樣的錯誤,我做錯了什麼?

回答

4

您發佈的代碼在使用或不使用ARC時都不起作用,因爲您需要在傳遞路徑名稱之前展開波浪號。

您發佈的代碼也泄漏了由CGDisplayCreateImageCGImageDestinationCreateWithURL返回的項目。下面是一個可以工作但不會泄漏的例子:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification 
{ 
    CGDirectDisplayID displayID = CGMainDisplayID(); 
    CGImageRef imageRef = CGDisplayCreateImage(displayID); //this is a screenshot (works fine) 

    NSString *path = [@"~/Desktop/public.png" stringByExpandingTildeInPath]; 
    [self savePNGImage:imageRef path:path]; 

    CFRelease(imageRef); 
} 

- (void)savePNGImage:(CGImageRef)imageRef path:(NSString *)path 
{ 
    NSURL *fileURL = [NSURL fileURLWithPath:path]; 
    CGImageDestinationRef dr = CGImageDestinationCreateWithURL((__bridge CFURLRef)fileURL, kUTTypePNG , 1, NULL); 

    CGImageDestinationAddImage(dr, imageRef, NULL); 
    CGImageDestinationFinalize(dr); 

    CFRelease(dr); 
} 
+2

「@」public.png「'很可能是作爲UTIType而不是文件名。然而,最好使用常量'kUTTypePNG'而不是自己滾動。也就是說,如果**是** UTIType,那麼他們仍然需要追加一個文件名。 – NSGod

+0

@NSGod Doh!感謝您指出了這一點。我會更新我的答案。 – jlehr