[IOS]Core Data(数据建模与保存)

Core Data–(数据建模与保存)

Demo功能介绍:

此Demo完成了对数据的保存和提取。

通过在.xcdatamodel中完成数据模型,在SampleData.plist中完成对数据的读取。

这个功能对persistent非常重要!

数据建模:

当文件很大时,会给一个连接,每次使用时,都会从这个链接中取出,如果文件很小时,直接保存到数据库。

[IOS]Core Data(数据建模与保存)_第1张图片


存储的都是dictionary类型,可以按键值对来检索。

tintColor用的是RGB,所以保存为一个dictionary类型。

如果是自己定制的数据模型,只要他继承与NSCoding和NSSecureCoding,就可以进行transformable。

最后,要将数据模型设置成为一个subclass!

数据模型:

import Foundation
import CoreData

extension NewDemosBowtie {

    @NSManaged var isFavorite: Bool
    @NSManaged var lastWorn: NSDate
    @NSManaged var rating: Double
    @NSManaged var searchKey: String?
    @NSManaged var timesWorn: Int32
    @NSManaged var photo: NSData?
    @NSManaged var tintColor: NSObject?
    @NSManaged var name: String?

}

代理:

在app开始时,要实现self.managedObjectContext的代理。

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        // context的传递。在viewcontroller里面可以直接访问managedObject
        let viewcontroller = self.window?.rootViewController as! ViewController
        viewcontroller.managedObject = self.managedObjectContext
        return true
    }

代码:

import UIKit
// 导入CoreData,如此才能使用相应的数据模型!
import CoreData

class ViewController: UIViewController {

    @IBOutlet weak var image: UIImageView!
    @IBOutlet weak var segmentController: UISegmentedControl!
    @IBOutlet weak var name: UILabel!
    @IBOutlet weak var ratingLabel: UILabel!
    @IBOutlet weak var TimesWornLabel: UILabel!
    @IBOutlet weak var LastWornLabel: UILabel!
    @IBOutlet weak var isFavoriteLabel: UILabel!

    var managedObject : NSManagedObjectContext!
    var current : NewDemosBowtie!

    override func viewDidLoad() {
        super.viewDidLoad()
        // 1. 插入演示数据
        insertSampleData()

        // 2. 取得访问请求!
        let fetchRequest = NSFetchRequest(entityName: "Bowtie")
        let title = segmentController.titleForSegmentAtIndex(0)
        // 在Bowtie中寻找满足searchKey的array
        fetchRequest.predicate = NSPredicate(format: "searchKey == %@", title!)
        // 取出数据
        do {
            let result = try managedObject.executeFetchRequest(fetchRequest)
            current = result[0] as! NewDemosBowtie
            showtoView(current)
        } catch {
            print("error")
        }
    }
    // reload view!
    func showtoView(bowtie : NewDemosBowtie) {
        image.image = UIImage(data: bowtie.photo!)
        image.layer.cornerRadius = 10
        image.layer.masksToBounds = true
        name.text = bowtie.name
        ratingLabel.text = " \(bowtie.rating)"
        TimesWornLabel.text = " \(bowtie.timesWorn)"

        let formatter = NSDateFormatter()
        formatter.timeStyle = .ShortStyle
        formatter.dateStyle = .LongStyle
        LastWornLabel.text = formatter.stringFromDate(bowtie.lastWorn)
        if bowtie.isFavorite == true {
            isFavoriteLabel.text = "YES!"
        } else {
            isFavoriteLabel.text = "NO!"
        }
        view.tintColor = bowtie.tintColor as! UIColor
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    // color 转换为UIColor
    func colorFrom(dic : NSDictionary) -> UIColor {
        let red = dic["Red"] as! CGFloat
        let green = dic["Green"] as! CGFloat
        let blue = dic["Blue"] as! CGFloat
        let color = UIColor(red: red, green: green, blue: blue, alpha: 1)
        return color
    }


    func insertSampleData() {
        let fetchRequest = NSFetchRequest(entityName: "Bowtie")
        fetchRequest.predicate = NSPredicate(format: "searchKey != nil")
        do {
            try managedObject.executeFetchRequest(fetchRequest)
        } catch {
            print("error")
        }
        let path = NSBundle.mainBundle().pathForResource("SampleData", ofType: "plist")
        let dataArray = NSArray(contentsOfFile: path!)

        for dict : AnyObject in dataArray! {
            let entity = NSEntityDescription.entityForName("Bowtie", inManagedObjectContext: managedObject)

            let bowtie = NewDemosBowtie(entity: entity!, insertIntoManagedObjectContext: managedObject)

            let dic = dict as! NSDictionary
            bowtie.setValue(dic["name"], forKey: "name")
            bowtie.setValue(dic["isFavorite"], forKey: "isFavorite")
            bowtie.setValue(dic["searchKey"], forKey: "searchKey")
            bowtie.setValue(dic["lastWorn"], forKey: "lastWorn")
            bowtie.setValue(dic["timesWorn"], forKey: "timesWorn")
            bowtie.setValue(dic["rating"], forKey: "rating")
            // 照片是先实例化再序列化
            let image = UIImage(named: dic["photo"] as! String)
            let photoData = UIImagePNGRepresentation(image!)
            bowtie.setValue(photoData, forKey: "photo")

            // color dictionary的转换
            bowtie.setValue(colorFrom(dic["tintColor"] as! NSDictionary), forKey: "tintColor")

            do {
                try managedObject.save()
            } catch {
                print("error!")
            }
            print("ok!")
        }
    }

    @IBAction func Rating(sender: AnyObject) {
        let controller = UIAlertController(title: "Do you wanna rate?", message: "please in the number between 0 and 5", preferredStyle: UIAlertControllerStyle.Alert)
        let YesAction = UIAlertAction(title: "YES!", style: UIAlertActionStyle.Default) { (action: UIAlertAction) -> Void in
            let textField = controller.textFields![0] as UITextField
            self.updateRateing(textField.text!)
        }
        let CancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)
        controller.addAction(YesAction)
        controller.addAction(CancelAction)
        controller.addTextFieldWithConfigurationHandler { (UITextField) -> Void in

        }
        self.presentViewController(controller, animated: true, completion: nil)
    }
    enum MyError: ErrorType {
        case NotExist
        case OutOfRange
    }

    func updateRateing(text : String) {
        current.rating = NSNumber(double: (text as NSString).doubleValue) as Double

        do {
            try managedObject.save()
            showtoView(current)
        } catch  {
            if current.rating > 5.0 {
                let controller = UIAlertController(title: "It is too large", message: nil, preferredStyle: .Alert)
                let CancelAction = UIAlertAction(title: "Try Again", style: UIAlertActionStyle.Cancel, handler: {
                    action in
                    self.Rating(self.current)
                })
                controller.addAction(CancelAction)
                self.presentViewController(controller, animated: true, completion: nil)
            } else {
                let controller = UIAlertController(title: "It is too small", message: nil, preferredStyle: .Alert)
                let CancelAction = UIAlertAction(title: "Try Again", style: UIAlertActionStyle.Cancel, handler: {
                    action in
                    self.Rating(self.current)
                })
                controller.addAction(CancelAction)
                presentViewController(controller, animated: true, completion: nil)
            }
            print("error!")
        }
    }
    @IBAction func Worn(sender: AnyObject) {
        let times = current.timesWorn
        current.timesWorn = times+1
        current.lastWorn = NSDate()
        do {
            try managedObject.save()
        } catch {
            print("error!")
        }
        showtoView(current)
    }

    @IBAction func SegmentChange(sender: UISegmentedControl) {
        let title = sender.titleForSegmentAtIndex(sender.selectedSegmentIndex)

        let fetchRequest = NSFetchRequest(entityName: "Bowtie")
        fetchRequest.predicate = NSPredicate(format: "searchKey == %@", title!)

        do {
            let result = try managedObject.executeFetchRequest(fetchRequest)
            self.current = result.last as! NewDemosBowtie
            showtoView(current)
        } catch {
            print("error!")
        }
    }
}

Demo下载:

Demo

你可能感兴趣的:([IOS]Core Data(数据建模与保存))