以下代码在模拟器上运行,但由于 img 为 nil 导致设备崩溃:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
for (NSString* path in userImages) {
NSLog(@"image at %@", path); //logs "image at userImage0.png"
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:path];
UIImage *img = [UIImage imageWithContentsOfFile:getImagePath];
unichar ch = [path characterAtIndex:9];
NSLog(@"Ch = %c", ch); //correctly logs "0"
if (ch == '0') {
[self.images insertObject:img atIndex:0]; //this throws the error
}
}
为什么在设备上运行而不是在模拟器上运行时 img nil?图像最初是这样保存的:
NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) objectAtIndex:0];
NSString *imageName = @"userimage0.png";
NSString *imagePath = [docsDir stringByAppendingPathComponent:imageName];
[UIImagePNGRepresentation(img) writeToFile:imagePath atomically:YES];