【发布时间】:2015-03-23 14:19:20
【问题描述】:
NSDocumentDirectory我是 iOS 新手。我试图构建一个简单的应用程序来更好地掌握核心数据和文件系统。我无法检索显然已存储的数据。
-我检查文件是否存在于路径中,它确实存在,但是当我尝试 NSLog 数据并返回 null 时。
非常感谢任何帮助。我的直觉是,这是一个范围界定或记忆保留问题,但我无法弄清楚。
这是 UIImagePicker 的保存方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *imageToAdd = info[UIImagePickerControllerOriginalImage];
NSData *pngsData = UIImagePNGRepresentation(imageToAdd);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [paths objectAtIndex:0];
NSString *filePath = [docPath stringByAppendingFormat:@"%@.png",[self getdateAndTime]];
NSError *error;
BOOL succcess = [pngsData writeToFile:filePath options:NSDataWritingAtomic error:&error];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSLog(@"The file exists");
}
if (error !=nil) {
NSLog(@"errorIS %@", error);
}
CoreDataStack *cds = [CoreDataStack defaultStack];
Photo *photo = [NSEntityDescription insertNewObjectForEntityForName:@"Photo" inManagedObjectContext:cds.managedObjectContext];
photo.photoName = filePath;
[cds saveContext];
[self dismissViewControllerAnimated:YES completion:nil];
[self.collectionView reloadData];
}
这是在集合视图中检索存储数据的代码
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
PhotoCollectionViewCell *photoCell = (PhotoCollectionViewCell*)[collectionView dequeueReusableCellWithReuseIdentifier:@"photoCell" forIndexPath:indexPath];
Photo *photo = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSLog(@"%@",photo.photoName);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imageLocation = [documentsDirectory stringByAppendingString:photo.photoName];
NSData *data = [NSData dataWithContentsOfFile:imageLocation];
UIImage *image = [UIImage imageWithData:self.testImageData];
NSLog(@"%@", data);
photoCell.cellImage.image = image;
photoCell.layer.borderColor = [[UIColor blackColor] CGColor];
photoCell.layer.borderWidth = 2.0;
return photoCell;
}
【问题讨论】:
-
仅供参考 - 您错误地使用了 Documentation 目录而不是 Documents 目录。
-
哇.. 谢谢你的收获。我修复了它,问题仍然存在
-
不要检查
error是否为!nil,检查返回变量(success) 是否为nil。 -
注意:OP 对路径的简单 NSLog 会显示问题。
标签: ios objective-c nsdata nsfilemanager nsdocumentdirectory