Swift Core Data预设值

时间:2019-01-16 15:19:35

标签: swift core-data

是否可以为核心数据设置一些预设值? 基本上添加了一些不可编辑的默认值,每个人都相等吗?

谢谢!

这是我获取数据的方式:

func attemptFetch(){
    let fetchRequest: NSFetchRequest<Course> = Course.fetchRequest()
    let dataSort = NSSortDescriptor(key: "title", ascending: true)
    fetchRequest.sortDescriptors = [dataSort]


    let controller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)

    controller.delegate = self
    self.controller = controller

    do {
        try controller.performFetch()
    } catch {
        let error = error as NSError
        print("\(error.debugDescription)")
    }
}

这就是我得到数组的方式:

if let objs = controller.fetchedObjects, objs.count > 0 {
        ....
}

1 个答案:

答案 0 :(得分:0)

所以我有两种选择。只需显示或实际添加即可。

  1. 显示它。将数组用于CoreData显示,并使用静态值添加数据。我认为这是最简单的。

var CoreDataStringArray = [String]()
var CoreDataImage1Array = [UIImage]()

func fetchData() {

//Static values

CoreDataStringArray = ["Item 1", "Item 2", Item 3", "Item 4", "Item 5"]
CoreDataImage1Array = [UIImage(named: "item1"),UIImage(named: "item2"),UIImage(named: "item3"),UIImage(named: "item4"),UIImage(named: "item5")]

//Now fetch the Core Data Values and the user will see a full list of them mixed together.

    } 

  1. You can add them on the first launch of the app. This how I save them, I run a for loop to siphon through each one.

//Inside Class (import CoreData above)

var CoreDataStringArray = [String]()
var CoreDataImage1Array = [UIImage]()

func fetchData() {

//Static values

CoreDataStringArray = ["Item 1", "Item 2", Item 3", "Item 4", "Item 5"]
CoreDataImage1Array = [UIImage(named: "item1"),UIImage(named: "item2"),UIImage(named: "item3"),UIImage(named: "item4"),UIImage(named: "item5")]

//Now fetch the Core Data Values and the user will see a full list of them mixed together.

    }