Database Reference
In-Depth Information
import Foundation
import UIKit
import CoreData
class Attachment: NSManagedObject {
@NSManaged var dateCreated: NSDate
@NSManaged var image: UIImage ?
@NSManaged var note: Note
}
Open Note.swift and delete the image property. Replace it with a property for the
attachments relationship:
@NSManaged var attachments: NSSet
The rest of your app is still depending on an image property, so you'll
get a compile error if you try to build the app. Add the following
computed property and helper method to the Note class: var image :
UIImage ? {
if let image = self . latestAttachment ()?.image {
return image
}
return nil
}
func latestAttachment() -> Attachment ? {
var attachmentsToSort = attachments . allObjects as [ Attachment ]
if attachmentsToSort. count == 0 {
return nil
}
attachmentsToSort. sort {
let date1 = $0. dateCreated . timeIntervalSinceReferenceDate
let date2 = $1. dateCreated . timeIntervalSinceReferenceDate
return date1 > date2
}
return attachmentsToSort[ 0 ]
}
This implementation uses a computed property, which gets the image from the
latest attachment. If there are several attachments, latestAttachment() will, as its
name suggests, grab the latest one and return it.
Next, open AttachPhotoViewController.swift to update it to create a new
Attachment object when the user chooses an image. Add the Core Data import to
the top of the file:
Search WWH ::




Custom Search