ios - 无法在 UITableViewCell 中的 UILabel 中显示来自 CoreData 的 Double

标签 ios swift core-data

在这个 TableView 中(override func tableView),我显示兴趣点,一些是默认加载的,其他的由用户加载。我可以检索托管对象的名称,但是当尝试显示位置时,它失败了。

我无法在 TableViewCell 中显示纬度和经度。如果我使用 name 关键字,名称就会出现。也许我应该对数字进行某种转换,但是在哪里呢?

我也收到了这个警告:

CoreData: warning: Unable to load class named 'PRODUCT_MODULE_NAME.ArcheoPOI' for entity 'ArcheoPOI'. Class not found, using default NSManagedObject instead.

这是我的NSManagedContext

enter image description here

import UIKit
import CoreData

import CoreLocation

class AppiaTVC: UITableViewController, UITableViewDataSource, UITableViewDelegate {


    var places : [NSManagedObject] = []

    let myLocationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        //MARK : good way to set the reuse id of the cell
        //        tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell") //alternative to put it in the
        //MARK : good way to set the table title
        title = "\"All the POI\""


    }





    //MARK: - Added for fetching data from CoreData
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)

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

        let managedContext = appDelegate.managedObjectContext!      //needed to handel mangedObject (saving and fetching entries)

        //2
        let fetchRequest = NSFetchRequest(entityName:"ArcheoPOI")

        //3
        var error: NSError?

        let fetchedResults = managedContext.executeFetchRequest(fetchRequest, error: &error) as? [NSManagedObject]

        if let results = fetchedResults {
            places = results
        } else {
            println("Could not fetch \(error), \(error!.userInfo)")
        }
    }




    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Potentially incomplete method implementation.
        // Return the number of sections.
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete method implementation.
        // Return the number of rows in the section.
        return places.count
    }


    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("appiaCellID", forIndexPath: indexPath) as! AppiaTVCell

        cell.backgroundColor = UIColor.blueColor()
        if indexPath.row % 2 == 0 {
            //            cell.backgroundColor = UIColor(red: 143 / 255, green: 204 / 255, blue: 255 / 255, alpha: 1)
            //            cell.sweetTextView.backgroundColor = UIColor(red: 63 / 255, green: 159 / 255, blue: 255 / 255, alpha: 1)

        } else {
            //            cell.backgroundColor = UIColor(red: 63 / 255, green: 159 / 255, blue: 255 / 255, alpha: 1)
            //            cell.sweetTextView.backgroundColor = UIColor(red: 143 / 255, green: 204 / 255, blue: 255 / 255, alpha: 1)
        }


        let singlePlace = places[indexPath.row]
        //KVC is the only way to access data in CoreData (can't use a property) butwe could also use a more natural object-style person.name
        //        cell.textLabel!.text = singlePlace.valueForKey("name") as? String
        cell.cellNameLabel.text = singlePlace.valueForKey("name") as? String
        cell.cellLatitudeLabel.text = singlePlace.valueForKey("latitude") as? String //if I use "name" it works
        cell.cellLongitudeLabel.text = singlePlace.valueForKey("longitude") as? String //if I use "name" it works

        return cell
    }




    @IBAction func addPlaceButtonPressed(sender: UIBarButtonItem) {

        var alert = UIAlertController(title: "New place", message: "Add a new place", preferredStyle: .Alert)

        let saveAction = UIAlertAction(title: "Save", style: .Default) { (action: UIAlertAction!) -> Void in

            let textField = alert.textFields![0] as! UITextField
            self.saveName(textField.text) //self.names.append(textField.text)
            self.tableView.reloadData()
        }

        let cancelAction = UIAlertAction(title: "Cancel", style: .Default) { (action: UIAlertAction!) -> Void in
        }

        alert.addTextFieldWithConfigurationHandler {
            (textField: UITextField!) -> Void in
        }

        alert.addAction(saveAction)
        alert.addAction(cancelAction)

        presentViewController(alert,
            animated: true,
            completion: nil)

    }




    //MARK: - save data to CoreData - this function is called by the addName button
    func saveName(name: String) {
        //1
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

        let managedContext = appDelegate.managedObjectContext!

        //2
        let entity =  NSEntityDescription.entityForName("ArcheoPOI", inManagedObjectContext: managedContext)   //NSEntityDescription is required

        let place = NSManagedObject(entity: entity!, insertIntoManagedObjectContext:managedContext)


        myLocationManager.startUpdatingLocation()
        let lat = myLocationManager.location.coordinate.latitude
        let lon = myLocationManager.location.coordinate.longitude
        myLocationManager.stopUpdatingLocation()
        println("************************")
        println(lat)
        println(lon)
        println("************************")


        //3
        place.setValue(name, forKey: "name")
        place.setValue(lat, forKey: "latitude")
        place.setValue(lon, forKey: "longitude")

        //4
        var error: NSError?
        if !managedContext.save(&error) {

            println("Could not save \(error), \(error?.userInfo)")

        }
        //5
        places.append(place)
    }




    //MARK - delete NSManagedObject
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

        switch editingStyle {

        case UITableViewCellEditingStyle.Delete:
            // remove the deleted item from the model
            let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
            let managedContext:NSManagedObjectContext = appDelegate.managedObjectContext!


            managedContext.deleteObject(places[indexPath.row] as NSManagedObject)
            places.removeAtIndex(indexPath.row)

            managedContext.save(nil)

            //tableView.reloadData()
            // remove the deleted item from the `UITableView`
            self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)

        default:
            return

        }
    }




    @IBAction func BackButtonPressed(sender: UIBarButtonItem) {

        dismissViewControllerAnimated(true , completion: nil)

    }


}

最佳答案

将您的代码更改为

let latitude = singlePlace.valueForKey("latitude")
let longitude = singlePlace.valueForKey("longitude")
cell.cellLatitudeLabel.text = "\(latitude)" //if I use "name" it works
cell.cellLongitudeLabel.text = "\(longitude)" //if I use "name" it works

我还强烈建议您创建一个类来管理您的实体。您可以找到有关如何操作的良好说明 here .本教程是在 objective-c 中,但从那以后没有太大变化;)

然后您将能够调用 singlePlace.latitutde 而不是使用 valueForKey

关于ios - 无法在 UITableViewCell 中的 UILabel 中显示来自 CoreData 的 Double,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31920314/

相关文章:

objective-c - 在 swift 中使用 objective-c 中的静态字符串

iphone - 在 iPhone 上下载、保存和播放 mp3

ios - 无法在 Swift for 循环中更改核心数据属性

ios - ipa 和 xcarchive 之间的区别?

php - NSObject 到 json?

jQuery Mobile + Phonegap : Page Header and Contents go Blank after Transition Completes

ios - Swift:使用scenekit 中的projectPoint 随时间获取并保存更新的SCNNode

ios - 我的 Xcode 项目坏了吗

ios - 点击 addChild viewController 不起作用

ios - 如何获取 UISwitch 的值?