[__NSArrayM insertObject:atIndex:]:object不能为nil' - 图片

时间:2014-02-18 21:27:42

标签: ios image uiimage load save

我正在制作迷你游戏。

在游戏中,用户可以选择自己的照片,并在游戏中使用它们。

当我选择图片时,它工作正常,并将它们保存到应用程序中。

但是当我将图片加载到游戏中时,我会收到此错误

 [__NSArrayM insertObject:atIndex:]: object cannot be nil

我认为这是因为该应用无法找到图片。但我不明白为什么。 :-D

是的我是Xcode的新手:-D

我的代码看起来像这样

- (void)loadCellImages 
{
    [self unloadCellImages];
    for (int i=1;i<(totalcolors+1);i++) 
    {
        imageSaveLoad *imgSL = [[imageSaveLoad alloc] init];     
        [cellImages addObject:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@-%d",[imgSL loadImage:@"Photo-"],i] ofType:@"png"]]];
    }
}

我加载并保存图片:

imageSaveLoad.m

//saving an image
- (void)saveImage:(UIImage*)image forKey:(NSString*)imageName
{
    NSData *imageData = UIImagePNGRepresentation(image);
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = paths[0];
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", imageName]];
    [fileManager createFileAtPath:fullPath contents:imageData attributes:nil];

    NSLog(@"image saved %@",imageName);
}

//removing an image
- (void)removeImage:(NSString*)fileName
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = paths[0];
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", fileName]];
    [fileManager removeItemAtPath: fullPath error:NULL];
    NSLog(@"image removed");
}

//loading an image
- (UIImage*)loadImage:(NSString*)imageName
{
   // NSLog(@"load %@",imageName);

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = paths[0];
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", imageName]];
    return [UIImage imageWithContentsOfFile:fullPath];

}

1 个答案:

答案 0 :(得分:0)

您正在将图片保存到NSDocumentDirectory,但尝试从主套装中加载:

[cellImages addObject:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@-%d",[imgSL loadImage:@"Photo-"],i] ofType:@"png"]]];

你可能只想要:

[cellImages addObject:[imgSL loadImage:[NSString stringWithFormat:@"Photo-", i]]];

您可以将mainBundle用于与您的应用捆绑在一起的图片(和资源)。

编辑: 为确保正确保存图片,您还应检查createFileAtPath:contents:attributes:的返回BOOL