我有3个实体(用户,相册和照片),具有以下属性。 我无法读取照片(相册1:<->>许多照片)中的数据。 这就是我保存数据的方式
var managedContext: NSManagedObjectContext!
var currentUser: User!
@IBAction func saveButtonTapped(_ sender: Any) {
let album = Album(context: managedContext)
album.albumMainPhoto = photoArray[0].jpegData(compressionQuality: 1.0) as! NSData
album.albumDescription = photoDescriptionArray[0]
album.numberOfPhotos = Int16(photoArray.count)
let photos = Photo(context: managedContext)
photos.colorAsHex = "hexTest"
photos.photo = photoArray[0].jpegData(compressionQuality: 1.0) as! NSData
photos.photoDescription = "descTest"
photos.photoStyle = "styleTest"
album.addToAlbumToPhotos(photos)
currentUser?.addToUserToAlbum(album)
do {
try managedContext.save()
} catch let error as NSError {
print("save error: \(error), description: \(error.userInfo)")
}
dismiss(animated: true, completion: nil)
}
然后我通过
检索数据guard let album = currentUser?.userToAlbum?[indexPath.row] as? Album,
let albumTitle = album.albumDescription as String?,
let albumPhotosCount = album.numberOfPhotos as Int16?,
let albumMainPhoto = album.albumMainPhoto as NSData? else {
return
}
guard let photos = Albums?.albumToPhotos?[indexPath.row] as? Photo,
let photodesc = photos.photoDescription as String?,
let photoImage = photos.photo as NSData?
else {
return
}
第一个选项(保护相册)可以正常工作,我无法阅读albumDescription,numberOfPhotos和图片相册MainPhoto。当我尝试在照片上使用它时,它无法读取数据。我仍然是coreData的新手,所以我可能做错了事。
答案 0 :(得分:0)
我能够用此获取数据:
guard let album = currentUser?.userToAlbum?[indexPath.row] as? Album,
let albumTitle = album.albumDescription as String?,
let albumPhotosCount = album.numberOfPhotos as Int16?,
let albumMainPhoto = album.albumMainPhoto as NSData?,
let photos = album.albumToPhotos?[indexPath.row] as? Photo,
let photosDes = photos.photoDescription as String?
else {
return
}