相关联的文件的使用情景:In both scenarios, you must make a small change to the application’s Info.plist file. Your app should already declare a Document Types (CFBundleDocumentTypes) array that declares the file types your app can open.
For each file type dictionary in that array, if that file type should be treated as a potentially related type for open and save purposes, add the key NSIsRelatedItemType with a boolean value of YES.(http://stackoverflow.com/)
写出文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
var sp = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) if sp.count > 0{ var url = NSURL(fileURLWithPath: "\(sp[0])/data.txt") // println(url) var data = NSMutableData() data.appendData("Hello Swift\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!) data.writeToFile(url!.path!, atomically: true) }
读取文件
1 2 3 4 5 6 7 8
// 两种加载文件方式 varLoaddata = NSData(contentsOfFile: url!.path!) var str = NSString(data: data, encoding: NSUTF8StringEncoding) var str1 = NSString(contentsOfURL: url!, encoding: NSUTF8StringEncoding, error: nil) println("load data : \(str) and \(str1)")
应用程序首选项数据
应用程序首选项数据可以方便的保存一些较小的数据,它不能存储很大的数据。
它以 key/value 方式存储数据,所以特别简单快捷。
存储首选项数据
1 2 3 4 5 6 7 8 9 10 11 12
@IBOutletweakvar inputText: UITextView! @IBActionfuncsaveBtn(sender: AnyObject) { var ud = NSUserDefaults.standardUserDefaults() ud.setObject(inputText.text, forKey: "data") println("Saved") }
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("UsingData.sqlite") println(url) //打印数据库地址 var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }()
读取数据
定义变量
1 2
var dataArr:Array<AnyObject> = [] var context:NSManagedObjectContext!
读取数据
1 2 3 4 5 6
context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext var f = NSFetchRequest(entityName:"Users"); dataArr = context.executeFetchRequest(f, error: nil)!
渲染界面
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
// Configure the cell...
var label = cell.viewWithTag(2) as! UILabel
var name = dataArr[indexPath.row].valueForKey("name") as! String
var age = dataArr[indexPath.row].valueForKey("age")
label.text = "name: \(name),age:\(age!)"
return cell
修改数据
从数据库获取指定数据
1 2 3 4 5 6 7 8 9 10 11
//UsersTableViewController:
var data = dataArr[indexPath.row] as! NSManagedObject