简体   繁体   English

iOS9-将字符串保存到核心数据

[英]iOS9 - Saving a string to Core Data

I know this question has been asked and answered many times but no matter how many solutions I try, I can't get it to work. 我知道这个问题已经被问过很多次,但是无论我尝试多少解决方案,我都无法解决。

So, my application will store user information about the current user that is logged in. I want to store it as a simple User object in Core Data. 因此,我的应用程序将存储有关当前登录用户的用户信息。我想将其作为简单的User对象存储在Core Data中。

I've created a new entity Called UserData with following attributes: 我用以下属性创建了一个名为UserData的新实体:

name
username
profilePicture

When the user logs in, these values are fetched from a server and shall be stored locally in Core Data. 当用户登录时,将从服务器获取这些值,并将这些值本地存储在Core Data中。

I have generated NSManagedObject subclasses for my entity and ended up with the following two classes 我为我的实体生成了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

}

and

//  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?

}

There are two functions called whenever the username should be saved or obtained from Core Data 每当应保存用户名或从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!
}

This is my first try to use core data and it seems like I'm missing something. 这是我第一次尝试使用核心数据,似乎丢失了一些东西。 Can anyone see what could be wrong here? 谁能看到这里有什么问题吗? I'm not sure if the data is saved correctly and the results from the fetchRequest is an empty array. 我不确定数据是否正确保存,并且fetchRequestresults是否为空数组。

Hopfully this will answer part of your question "I'm not sure if the data is saved correctly" 希望可以回答您的部分问题“我不确定数据是否正确保存”

Instructions for Xcode 6.0.1 Xcode 6.0.1的说明

  1. Xcode > Open > YourProject Xcode>打开> YourProject
  2. Xcode > Product > Run Xcode>产品>运行
  3. Xcode > Window > Devices Xcode>窗口>设备
  4. (Column 1 - select) Devices > YourDeviceName (第1列-选择)设备> YourDeviceName
  5. (Column 2 - select) Installed Apps > YourAppName (第2列-选择)已安装的应用程序> YourAppName
  6. (Column 2 - select) Cog under 'Installed Apps' list (第2列-选择)“已安装的应用”列表下的齿轮
  7. (Pop-Up - select) Download Container... Save to location (弹出窗口-选择)下载容器...保存到位置
  8. Right click on 'YourAppName.xcappdata' 右键单击“ YourAppName.xcappdata”
  9. Select 'Show Package Contents' 选择“显示包装内容”
  10. AppData > Documents > YourDatabase AppData>文档> YourDatabase

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM