I am experiencing a really strange problem with saving files to disk and then reading them again.
First, I decode an animated .GIF image and store the frames in an NSArray of NSData objects. This works fine.
When I create a UIImage with one of these NSData objects, the image appears garbled even though the GIF image data is okay. Apparently it is not clear to the system that the NSData contains GIF image data.
To work around this, I decided to write the NSData objects to files on the disk with a .gif extension in the file name. When I then load them into UIImages using [UIImage imagenamed:@"..."] everything is okay and the images are displayed correctly.
Unfortunately the UIImages need some internal converting because they take a while to display, even though they are only 16 kb in size. No problem, I'll just load them in a separately detached thread, so the image loading will not stall the user interface:
Code:
[NSThread detachNewThreadSelector:@selector(writeFrames) toTarget:self withObject:nil];
I write the files using:
Code:
[[NSFileManager defaultManager] createFileAtPath :file contents:nil attributes:nil];
NSFileHandle *outFile = [NSFileHandle fileHandleForWritingAtPath:file];
fcntl([outFile fileDescriptor], F_NOCACHE, 1);
// Truncate the output file since it may contain data
[outFile truncateFileAtOffset:0];
// Write data to outFile
[outFile writeData:GIF_framesData];
// close the file
[outFile synchronizeFile];
[outFile closeFile];
(I am using the NSFilehandle with no caching because I first thought I had a caching problem.)
After writing the files the system cannot find any files at all:
Code:
[[NSFileManager defaultManager] directoryContentsAtPath:path]
...will return no files whatsoever, even though they really are present on the disk and the path is correct. I know this, because of the following:
This happens ONLY when running the app stand-alone on the iPhone. In the simulator, it works fine. Also on the iPhone using the debugger from within XCode, it works fine.
Everything always seems to run fine until I disconnect the iPhone and run the app on it with no XCode attached. Then the filemanager returns zero files.
When running the file handling in the main thread, instead of a separate thread, everything also works fine, except that the user interface stalls when loading the GIF files (which is unwanted).
If anyone knows:
- how to display NSData objects containing GIF image data without saving them to disk first
- how to store files and then immediately read them again without the filemanager losing them
I'd be very, very happy. I am basically at my wit's end.
Thanks!
Martin