开发者

NSDATA writeToFile crashes without a reason

I am downloading images from a url using NSDATA and savi开发者_运维问答ng them to local file system using

NSData *dataForStorage = [NSData dataWithData:UIImagePNGRepresentation(img)];


    BOOL saveResult=[ dataForStorage writeToFile:jpegFilePath options:NSDataWritingAtomic error:&error];
    NSLog(@"Write returned error: %@", [error localizedDescription]);

My app crashes randomly without even giving a message, though some files are saved (again randomly). When I run the app in Debug mode, I frequently see "EXC_BAD_ACCESS" but continuing execution succeeds in saving some of the files.

This code is executed in background from:

[self performSelectorInBackground:@selector(loadImageInBackground:) withObject:arr];

Please suggest.


One of the problems in your code is that your running code in a thread without an autorelease pool but are using functions that would require one. Put the following code into the loadImageInBackground method:

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

// existing code

[pool drain];

This is probably just one of several problems. For further assistance, we need to see the stack trace of the crash.


Just a wild guess : arr is an autoreleased object, so, sometimes it gets deallocated before your selector gets called. Try using [arr copy] and release it after saving it.


I was having the EXACT same problem, but it turned out that the problem was something else: my URL was getting release prematurely. In the end this is what I did and it worked:

I made this call:

[self performSelectorInBackground:@selector(downloadData:) withObject:nil];

And this is the method:

// URL - (NSString) URL for file
// filePath - (NSString) save location on device
-(void)download:(NSString *)URL
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:URL]];
    [data writeToFile:filePath atomically:YES];
    [pool release];
}

So I think that your download code is correct, but there is some other variable that is getting deallocated early (possibly your path).

Hope this helps! I know the other answers on this page worked for me.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜