SWIFT 之CoreData初試

來源:互聯網
上載者:User

標籤:

SWIFT中使用CoreData來儲存本機資料,在建立項目的時候把 "Use Core Data"選項選上

項目建立完成後點擊尾碼為 .xcdatamodeld的那個檔案,點擊右下角"Add Entity"添加一個Entity後可以修改其名稱,接著在"Attributes"下面點擊“+”號添加一個

Attribute

 

 

接著就可以上代碼操作了,首先先添加引用

import CoreData

//It‘s necessary to code these two rows if you want to use CoreData

var applicationDelegate = UIApplication.sharedApplication().delegate as AppDelegate

var managedObjectContext = applicationDelegate.managedObjectContext

//Get the entity by entityName        

var entity = NSEntityDescription.entityForName("Notes", inManagedObjectContext: managedObjectContext!)

//Get the ManagedObject

var title = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedObjectContext)

//Set the ManagedObject Value for key

title.setValue(text, forKey: "title")

 

var error: NSError?

//Save content

if(managedObjectContext?.save(&error) == nil){

 }

 

//Get data from the CoreData

var applicationDelegate = UIApplication.sharedApplication().delegate as AppDelegate

var managedObjectContext = applicationDelegate.managedObjectContext

var fetchRequest = NSFetchRequest(entityName: "Notes")

        

var error:NSError?

var fetchResults = managedObjectContext?.executeFetchRequest(fetchRequest, error: &error) as [NSManagedObject]?

if let results = fetchResults{

      var  notes = results

}else{

        println(error)

}

 

SWIFT 之CoreData初試

相關文章

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.