NSData dataWithContentsOfFile 返回值为nil

来源:互联网 发布:爵士舞蹈教学软件 编辑:程序博客网 时间:2024/06/05 01:56
  • NSData *imageData = [NSData dataWithContentsOfFile:fullPath]; 我在这里遇到的是自己给自己挖了坑,贴出来给给大家看看.
    先看一段代码
UIImage *image = [self.images objectForKey:appM.icon];    if (image) {        cell.imageView.image = image;        NSLog(@"%zd -- 此处使用了内存缓存中的图片",indexPath.row);    }else{        /**         * 已下载的图片,保存到内存缓存中         */        //保存到沙盒缓存        NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];        //获得图片的名称        NSString *filename = [appM.icon lastPathComponent];        //拼接图片的全路径        NSString *fullPath = [caches stringByAppendingPathComponent:filename];        //检查磁盘缓存,图片是否存在        NSData *imageData = [NSData dataWithContentsOfFile:fullPath];        if (imageData) {            UIImage *image  = [UIImage imageWithData:imageData];            cell.imageView.image = image;            NSLog(@"%zd -- 此处使用了 磁盘 缓存中的图片",indexPath.row);            //把图片保存到内存缓存            [self.images setObject:image forKey:appM.icon];        }else{        NSURL *url = [NSURL URLWithString:appM.icon];        NSData *data = [NSData dataWithContentsOfURL:url];        UIImage *image = [UIImage imageWithData:data];        cell.imageView.image = image;        //把图片放到内存缓存        [self.images setObject:image forKey:appM.icon];        //同时,写入数据到沙盒        [iamgeData writeToFile:fullPath atomically:YES];        NSLog(@"%zd ---- 下载 - ",indexPath.row);        }    }

上面这段示例程序主要是想从网络上下载图片并显示到TableView上,下载好的图片放到内存缓存中,并写入磁盘,当程序再次启动,首先检查磁盘中有没有下载了相关的图片,如果有则从磁盘中读取并加载到内存缓存,如果没有则下载并放到内存缓存并写入磁盘.

  • 然而在调试过程中发现数据一直没法写入到沙盒,并且发现[NSData dataWithContentsOfFile:fullPath]返回值一直是nil,于是网上找了一些关于dataWithContentsOfFile出错的原因,也是不尽相同.
  • 后来沉下心来发现自己犯了很二的错误,原因出在

    NSData *imageData = [NSData dataWithContentsOfFile:fullPath];
    与这一行 [iamgeData writeToFile:fullPath atomically:YES];

  • imageData在程序一开始运行的时候返回值就是nil,程序执行到 [iamgeData writeToFile:fullPath atomically:YES];这里的时候什么都没有写入到磁盘中,造成了一个死循环.

  • 写入磁盘那一行应为[data writeToFile:fullPath atomically:YES];

就是自己逻辑不清晰,命名不规范挖的坑