简体   繁体   English

在Swift中访问NSManagedObject属性

[英]Access NSManagedObject properties in Swift

I'm getting NSManagedObjects from core data and trying to populate tableview. 我从核心数据中获取NSManagedObjects,并尝试填充tableview。 When i get the objects array i'm able to access and print the property. 当我得到对象数组时,我可以访问和打印属性。 But when i try to access the same in tableView cellForRowAtIndexpath i'm getting nil value. 但是,当我尝试在tableView cellForRowAtIndexpath中访问相同的对象时,我得到的值为零。 Why is this happening? 为什么会这样呢?

在此处输入图片说明

{


import UIKit

class NotesView: UIViewController, UITableViewDelegate, UITableViewDataSource { 类NotesView:UIViewController,UITableViewDelegate,UITableViewDataSource {

//MARK:- IBOutlets
@IBOutlet weak var NotesTable: UITableView!
var notesArray = [Notes]()

//MARK:- ViewController Delegates
override func viewDidLoad() {
    super.viewDidLoad()

    notesArray = Notes.getNotes()
    for value in notesArray{
        print(value.body!)
    }
    print(notesArray[0].body)
    NotesTable.delegate = self
    NotesTable.dataSource = self
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}
//MARK:- TabelView Delegate Methods
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return notesArray.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("NotesTableCell")
    for value in notesArray{
        print("Value = \(value.body)")
    }
    cell?.textLabel?.text = (notesArray[indexPath.row]).body!

    return cell!
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let vc = UIStoryboard(name: "Main",bundle: nil).instantiateViewControllerWithIdentifier("NewNoteVC") as! NewNoteView
    vc.display = true
    vc.text = notesArray[indexPath.row].body!
    self.presentViewController(vc, animated: false, completion: nil)
}

} }

您应该首先确认位置[index.row]的对象不是nil

I found that NSManagedObjects lifetime is less ie we can't store them in an array or something and use it later. 我发现NSManagedObjects的生存期较短,即我们无法将它们存储在数组或其他内容中,以后再使用。 So i started using NSManagedSubClasses and using them instead. 所以我开始使用NSManagedSubClasses并改为使用它们。

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

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