簡體   English   中英

iOS9-將字符串保存到核心數據

[英]iOS9 - Saving a string to Core Data

我知道這個問題已經被問過很多次,但是無論我嘗試多少解決方案,我都無法解決。

因此,我的應用程序將存儲有關當前登錄用戶的用戶信息。我想將其作為簡單的User對象存儲在Core Data中。

我用以下屬性創建了一個名為UserData的新實體:

name
username
profilePicture

當用戶登錄時,將從服務器獲取這些值,並將這些值本地存儲在Core Data中。

我為我的實體生成了NSManagedObject子類,並得到了以下兩個類

//  UserData.swift
//  Created by xxx on 2015-10-14.

import Foundation
import CoreData

class UserData: NSManagedObject {

// Insert code here to add functionality to your managed object subclass

}

//  UserData+CoreDataProperties.swift
//  Created by xxx on 2015-10-14.

//  Choose "Create NSManagedObject Subclass…" from the Core Data editor menu
//  to delete and recreate this implementation file for your updated model.

import Foundation
import CoreData

extension UserData {

  @NSManaged var profilePicture: NSData?
  @NSManaged var username: String?
  @NSManaged var name: String?

}

每當應保存用戶名或從Core Data獲取用戶名時,都會調用兩個函數

func saveUsername(username: String) {

    let appDelegate =
    UIApplication.sharedApplication().delegate as! AppDelegate

    let managedContext = appDelegate.managedObjectContext

    let entity =  NSEntityDescription.entityForName("UserData",
        inManagedObjectContext:managedContext)

    let user = UserData(entity: entity!,
        insertIntoManagedObjectContext: managedContext)

    user.setValue(username, forKey: "name")

    do {
        try managedContext.save()
    } catch let error as NSError  {
        print("Could not save \(error), \(error.userInfo)")
    }
}

func getUsername() -> String{
    let appDelegate =
    UIApplication.sharedApplication().delegate as! AppDelegate

    let managedContext = appDelegate.managedObjectContext

    let fetchRequest = NSFetchRequest(entityName: "UserData")

    var users = [UserData]()

    do {
        let results =
        try managedContext.executeFetchRequest(fetchRequest)
        users = results as! [UserData]
    } catch let error as NSError {
        print("Could not fetch \(error), \(error.userInfo)")
    }
    return users[0].name!
}

這是我第一次嘗試使用核心數據,似乎丟失了一些東西。 誰能看到這里有什么問題嗎? 我不確定數據是否正確保存,並且fetchRequestresults是否為空數組。

希望可以回答您的部分問題“我不確定數據是否正確保存”

Xcode 6.0.1的說明

  1. Xcode>打開> YourProject
  2. Xcode>產品>運行
  3. Xcode>窗口>設備
  4. (第1列-選擇)設備> YourDeviceName
  5. (第2列-選擇)已安裝的應用程序> YourAppName
  6. (第2列-選擇)“已安裝的應用”列表下的齒輪
  7. (彈出窗口-選擇)下載容器...保存到位置
  8. 右鍵單擊“ YourAppName.xcappdata”
  9. 選擇“顯示包裝內容”
  10. AppData>文檔> YourDatabase

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM