NSManagedObject Subclasses
design screen:
SampleData.plist
Data Model:
Note:
photoData - (options select ) Allows External Storage
tintColor : Tansformable - 可转换的
Open Bow_Ties.xcdatamodeld
Editor\Create NSManagedObject Subclass….
Genenating:
==========================================
//Bowtie.swift :
import Foundation
import CoreData
class Bowtie: NSManagedObject {
}
//Bowtie+CoreDataProperties.swift
import Foundation
import CoreData
extension Bowtie {
@NSManaged var name: String?
@NSManaged var isFavorite: NSNumber?
@NSManaged var lastWorn: NSDate?
@NSManaged var rating: NSNumber?
@NSManaged var searchKey: String?
@NSManaged var timesWorn: NSNumber?
@NSManaged var photoData: NSData?
@NSManaged var tintColor: NSObject?
}
====================================================
func application(application: UIApplication,
didFinishLaunchingWithOptions
launchOptions: [NSObject: AnyObject]?) -> Bool {
// Save test bow tie
let bowtie = NSEntityDescription.insertNewObjectForEntityForName("Bowtie",inManagedObjectContext: managedObjectContext) as! Bowtie
bowtie.name = "My bow tie"
bowtie.lastWorn = NSDate()
do {
try managedObjectContext.save()
} catch let error as NSError {
print("Saving error: \(error.localizedDescription)")
}
// Retrieve test bow tie
do {
let request = NSFetchRequest(entityName: "Bowtie")
let ties =
try managedObjectContext.executeFetchRequest(request)
as! [Bowtie]
let sample : Bowtie = ties[0]
print("Name: \(sample.name), Worn: \(sample.lastWorn)")
} catch let error as NSError {
print("Fetching error: \(error.localizedDescription)")
}
return true
}
ful coding:
func application(application: UIApplication,
didFinishLaunchingWithOptions
launchOptions: [NSObject: AnyObject]?) -> Bool {
let viewController = window!.rootViewController as! ViewController
viewController.managedContext = managedObjectContext
return true
}
/*
* Copyright (c) 2016 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
import CoreData
class ViewController: UIViewController {
@IBOutlet weak var segmentedControl: UISegmentedControl!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var ratingLabel: UILabel!
@IBOutlet weak var timesWornLabel: UILabel!
@IBOutlet weak var lastWornLabel: UILabel!
@IBOutlet weak var favoriteLabel: UILabel!
var managedcontext: NSManagedObjectContext!
var currentBowtie: Bowtie!
override func viewDidLoad() {
super.viewDidLoad()
//1
insertSampleData()
//2
let request = NSFetchRequest(entityName:"Bowtie")
let firstTitle = segmentedControl.titleForSegmentAtIndex(0)
request.predicate =
NSPredicate(format:"searchKey == %@", firstTitle!)
do {
//3
let results =
try managedContext.executeFetchRequest(request) as! [Bowtie]
//4
populate(results.first!)
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
}
@IBAction func segmentedControl(control: UISegmentedControl) {
let selectedValue = control.titleForSegmentAtIndex(control.selectedSegmentIndex)
let request = NSFetchRequest(entityName: "Bowtie")
request.predicate = NSPredicate(format: "searchKey == %@", selectedValue!)
do {
let results =
try managedcontext.executeFetchRequest(request) as! [Bowtie]
currentBowtie = results.first
populate(currentBowtie)
} catch let error as NSError {
print(" Could not fetch \(error), \(error.userInfo)")
}
}
@IBAction func wear(sender: AnyObject) {
let times = currentBowtie.timesWorn!.integerValue
currentBowtie.timesWorn = NSNumber(integer: (times + 1))
currentBowtie.lastWorn = NSDate()
do {
try managedContext.save()
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
populate(currentBowtie)
}
@IBAction func rate(sender: AnyObject) {
let alert = UIAlertController(title: "New Rating",
message: "Rate this bow tie",
preferredStyle: UIAlertControllerStyle.Alert)
let cancelAction = UIAlertAction(title: "Cancel",
style: .Default,
handler: { (action: UIAlertAction!) in
})
let saveAction = UIAlertAction(title: "Save",
style: .Default,
handler: { (action: UIAlertAction!) in
let textField = alert.textFields![0] as UITextField
self.updateRating(textField.text!)
})
alert.addTextFieldWithConfigurationHandler {
(textField: UITextField!) in
textField.keyboardType = .NumberPad
}
alert.addAction(cancelAction)
alert.addAction(saveAction)
presentViewController(alert,
animated: true,
completion: nil)
}
//Insert sample data
func insertSampleData() {
let fetchRequest = NSFetchRequest(entityName: "Bowtie")
fetchRequest.predicate = NSPredicate(format: "searchKey != nil")
let count = managedContext.countForFetchRequest(fetchRequest, error: nil)
if count > 0 {return }
let path = NSBundle.mainBundle().pathForResource("SampleData", ofType: "plist")
let dataArray = NSArray(contentsOfFile: path!)!
for dict : AnyObject in dataArray {
let entity = NSEntityDescription.entityForName("Bowtie",
inManagedObjectContext: managedContext)
let bowtie = Bowtie(entity: entity!,
insertIntoManagedObjectContext: managedContext)
let btDict = dict as! NSDictionary
bowtie.name = btDict["name"] as? String
bowtie.searchKey = btDict["searchKey"] as? String
bowtie.rating = btDict["rating"] as? NSNumber
let tintColorDict = btDict["tintColor"] as? NSDictionary
bowtie.tintColor = colorFromDict(tintColorDict!)
let imageName = btDict["imageName"] as? String
let image = UIImage(named:imageName!)
let photoData = UIImagePNGRepresentation(image!)
bowtie.photoData = photoData
bowtie.lastWorn = btDict["lastWorn"] as? NSDate
bowtie.timesWorn = btDict["timesWorn"] as? NSNumber
bowtie.isFavorite = btDict["isFavorite"] as? NSNumber
}
}
func colorFromDict(dict: NSDictionary) -> UIColor {
let red = dict["red"] as! NSNumber
let green = dict["green"] as! NSNumber
let blue = dict["blue"] as! NSNumber
let color = UIColor(red: CGFloat(red)/255.0,
green: CGFloat(green)/255.0,
blue: CGFloat(blue)/255.0,
alpha: 1)
return color
}
func populate(bowtie: Bowtie) {
imageView.image = UIImage(data:bowtie.photoData!)
nameLabel.text = bowtie.name
ratingLabel.text = "Rating: \(bowtie.rating!.doubleValue)/5"
timesWornLabel.text =
"# times worn: \(bowtie.timesWorn!.integerValue)"
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .ShortStyle
dateFormatter.timeStyle = .NoStyle
lastWornLabel.text = "Last worn: " +
dateFormatter.stringFromDate(bowtie.lastWorn!)
favoriteLabel.hidden = !bowtie.isFavorite!.boolValue
view.tintColor = bowtie.tintColor as! UIColor
}
func updateRating(numericString: String) {
currentBowtie.rating = (numericString as NSString).doubleValue
do {
try managedcontext.save()
populate(currentBowtie)
} catch let error as NSError {
rate(currentBowtie)
print("Could not save \(error), \(error.userInfo)")
}
}
}