iOS Swift學習筆記 Core Data (一)Hello Core Data

來源:互聯網
上載者:User

標籤:swift   ios   coredata   

正在學習swift的Core Data,做個筆記,順便分享源碼


這個執行個體是一個很簡單的Table,通過右上方的Add按鈕可以添加新的使用者名稱。資料存放區在CoreData中,這樣,才不會丟失。


通過這個例子可以學會:

  1. 使用Xcode的model編輯器建立資料對象的model data。

  2. 添加新的記錄到CoreData中

  3. 從CoreData中擷取記錄集合

  4. 顯示記錄到table view中


這個例子十分簡單,還有很多可以改進的地方,比如,每次要操作managed class都需要訪問AppDelegate,讀取和儲存資料使用的是KVC(key-valuecoding )方式而不是類似於類操作的方式。


程式和源碼地址:

https://github.com/dnawym/StudySwift/tree/master/CoreData/HitList


650) this.width=650;" src="http://s3.51cto.com/wyfs02/M01/57/98/wKioL1Sf64bwXJgoAAEHDYWHhmc131.jpg" style="float:none;" title="螢幕快照 2014-12-28 下午6.02.39.png" alt="wKioL1Sf64bwXJgoAAEHDYWHhmc131.jpg" />

650) this.width=650;" src="http://s3.51cto.com/wyfs02/M01/57/9B/wKiom1Sf6tTAjanFAADno-1YoAw149.jpg" style="float:none;" title="螢幕快照 2014-12-28 下午6.01.41.png" alt="wKiom1Sf6tTAjanFAADno-1YoAw149.jpg" />

  • 在建立工程時選擇使用core data

650) this.width=650;" src="http://s3.51cto.com/wyfs02/M02/57/98/wKioL1Sf67OB22CfAAK8GaPdUXE496.jpg" title="螢幕快照 2014-12-28 下午2.26.13.png" alt="wKioL1Sf67OB22CfAAK8GaPdUXE496.jpg" />

  • 編輯.xcdatamodeld檔案,添加entity person,添加attribute name,類型為String

650) this.width=650;" src="http://s3.51cto.com/wyfs02/M02/57/9B/wKiom1Sf6yDw3XYgAAH0I8IPWO0906.jpg" title="螢幕快照 2014-12-28 下午2.26.30.png" alt="wKiom1Sf6yDw3XYgAAH0I8IPWO0906.jpg" />

  • 初始化,讀取和修改core data資料

    @IBOutlet weak var tableView: UITableView!    var people = [NSManagedObject]()
  • 從Core Data資料庫中讀取資料

    override func viewWillAppear(animated: Bool) {        let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate                let managedContext = appDelegate.managedObjectContext!                let fetchRequest = NSFetchRequest(entityName: "Person")                var error: NSError?                let fetchResults = managedContext.executeFetchRequest(fetchRequest, error: &error) as [NSManagedObject]?                if let results = fetchResults {            people = results        } else {            println("Could not fetch \(error), \(error!.userInfo)")        }    }
  • 讀取資料填入table view中

    // MARK: UITableViewDataSource    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {        return people.count    }        func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {        let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell                let person = people[indexPath.row]        cell.textLabel?.text = person.valueForKey("name") as String?                return cell    }


  • 添加使用者名稱並儲存到Core Data資料庫中

    @IBAction func addName(sender: AnyObject) {                var alert = UIAlertController(title: "New name", message: "Add a new name", preferredStyle: UIAlertControllerStyle.Alert)                let saveAction = UIAlertAction(title: "Save", style: .Default, handler: {            (action: UIAlertAction!) -> Void in            let textField = alert.textFields![0] as UITextField            self.saveName(textField.text)            self.tableView.reloadData()        })                let cancelAction = UIAlertAction(title: "Cancel", style: .Default, handler: {            (action: UIAlertAction!) -> Void in        })                alert.addTextFieldWithConfigurationHandler({            (textField: UITextField!) -> Void in        })                alert.addAction(saveAction)        alert.addAction(cancelAction)                presentViewController(alert, animated: true, completion: nil)    }        // MARK: private    func saveName(name: String) {        let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate        let managedContext = appDelegate.managedObjectContext!                let entity = NSEntityDescription.entityForName("Person", inManagedObjectContext: managedContext)                let person = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)                person.setValue(name, forKey: "name")                var error:NSError?        if !managedContext.save(&error) {            println("Could not save \(error), \(error?.userInfo)")        }                people.append(person)    }


本文出自 “吳亞明的部落格” 部落格,請務必保留此出處http://yaming.blog.51cto.com/6940049/1596991

iOS Swift學習筆記 Core Data (一)Hello Core Data

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.