【发布时间】:2018-07-14 05:09:16
【问题描述】:
这里的代码在集合视图上显示一个数组。它完全按照我想要的方式工作。
import UIKit
import CoreData
class collectionVIEW: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource{
var sam = ["3","j"]
var users = [User]()
@IBOutlet var theIssues: UICollectionView!
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return sam.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! whyCollectionViewCell
// cell.general.text = users[indexPath.row].userName
cell.general.text = sam[indexPath.row]
return cell
}
}
在我的第二个代码中。代码略微提醒调用核心数据并显示在单元格上。正如您在照片中看到的,没有可见的单元格。我想要做的就是让核心数据准确地显示在我在第一个代码集中能够做的事情。
import UIKit
import CoreData
class collectionVIEW: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource{
var sam = ["3","j"]
var users = [User]()
@IBOutlet var theIssues: UICollectionView!
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return users.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! whyCollectionViewCell
cell.general.text = users[indexPath.row].userName
// cell.general.text = sam[indexPath.row]
return cell
}
}
核心数据
import UIKit
import CoreData
class cdHandler: NSObject {
private class func getContext() -> NSManagedObjectContext {
let appdeleagetzz = UIApplication.shared.delegate as! AppDelegate
return appdeleagetzz.persistentContainer.viewContext
}
class func saveObject(userName: String) -> Bool {
let context = getContext()
let entity = NSEntityDescription.entity(forEntityName: "User", in: context)
let managedObject = NSManagedObject(entity: entity!, insertInto: context)
managedObject.setValue(userName, forKey: "userName")
do {
try context.save()
return true
} catch {
return false
}
}
class func fetchObject() -> [User]? {
let context = getContext()
var users: [User]? = nil
do {
users = try context.fetch(User.fetchRequest())
return users
} catch {
return users
}
}
}
【问题讨论】:
-
从核心数据加载用户数组的代码在哪里?
-
数组与核心数据无关,它只是在那个视图控制器中。 @Paulw11
-
代码显示
users数组被你的collectionView使用了。如何将数据放入该数组? -
var users = [User]() 是核心数据。要不要我把核心数据vc上传到这个问题
-
这声明了一个空的
User对象数组(并且可能User是您的NSManagedObject子类),但您需要实际从持久存储中获取数据到数组中。
标签: ios core-data uicollectionview uicollectionviewcell swift4