简体   繁体   中英

CoreData Fetch creates String from Double

I am querying HealthKit and saving the entries to CoreData: Here is my Fetch Request:

func queryCoreDataData () -> NSArray {
var context = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext!

var request = NSFetchRequest(entityName: "HKActiveEnergyBurned")
request.returnsObjectsAsFaults = false
var hkActiveEnergyBurned = context.executeFetchRequest(request, error: nil)! as [HKActiveEnergyBurned]
var activeEnergyBurnedData = (hkActiveEnergyBurned as NSArray).valueForKey("activeEnergyBurned_data") as NSArray  
println("CoreData Fetch activeEnergyBurnedData: \(activeEnergyBurnedData)")

return activeEnergyBurnedData
}

I print each entry to the console. The console shows this:

Saving to CoreData:
CD save activeEnergyBurned: 740.0
CD save activeEnergyBurned: 725.0
CD save activeEnergyBurned: 4.0
CD save activeEnergyBurned: 152.0
CD save activeEnergyBurned: 459.0

When I later Fetch the data some of the entries have become Strings!

CoreData Fetch activeEnergyBurnedData: (
"739.9999999999999",
    725,
    4,
    152,
    "459.0000000000001"
)

Here is a picture of my CoreData Model

CoreData模型

and the NSManaged Object:

import Foundation
import CoreData

class HKActiveEnergyBurned: NSManagedObject {

    @NSManaged var activeEnergyBurned_data: NSNumber
    @NSManaged var activeEnergyBurned_date: NSDate

}

I tried to google this, but nothing comes up. Maybe I am asking the wrong question. Does anyone know why this happen and how I can make sure that the values stay as double? (You may notice that the NSManaged Object comes up as NSNumber, I am not sure why that happens either). Any help would be very much appreciated. Thank you !

The type of the activeEnergyBurned_data is NSNumber however when you print it to console the description method is called. This method is needed to provide textual representation of the object. So that is why you see numbers printed in quotes. This method is inherited from NSObject protocol so that any object has a chance to provide textual representation for debugging or logging, etc.

Your numbers are printing surrounded by quotes when they contain a decimal point, but they are still stored as numbers. You can reproduce this trivially:

let array = [ 739.9, 725 ] as NSArray
println("\(array)")

Output:

(
    "739.9",
    725
)

String interpolation uses the description method (in this case), and this is just the way -[NSArray description] works. It's not a bug. If you don't like it, you'll have to convert the array to a string “manually” instead of relying on description .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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