Casting Int database value into CoreData issue - ios

I am trying to load some values from my firebase database directly into CoreData, the value in question is an integer but the issue is CoreData wants a Int64, Int32, or Int16, and it's not possible to downcast Ints in swift, So I am getting an error on the line of code where I assign the CoreData attribute to the database value. The database returns 0 (value will only be 0 or 1). Casting the database value as an Int64 is giving me an error. The bilateral_unilat attribute is of type Int64. How can I save an Int value into CoreData?
cdExercise.bilat_unilat = (exercise.childSnapshot(forPath: "bilat_unilat").value as! Int64)
this is the error:
Could not cast value of type 'NSTaggedPointerString' (0x7fff87a91958) to 'NSNumber' (0x7fff87b50b80).
in the debugger window I can print out a value of 0, which is the expected value, with this line of code:
po (exercise.childSnapshot(forPath: "bilat_unilat").value as! NSNumber)
Not sure what the issue is here

If you're attempting to get to a NSNumber as the end result, here's a couple of options
let aInt = snapshot.childSnapshot(forPath: "bilat_unilat").value as? Int ?? 0
let aNum = NSNumber(integerLiteral: aInt)
or just do it directly
let aNum = snapshot.childSnapshot(forPath: "bilat_unilat").value as! NSNumber
*note I omitted error handling for brevity and assumes the value of the bilat_unilat node is in fact an Int

The error
Could not cast value of type 'NSTaggedPointerString' (0x7fff87a91958) to 'NSNumber' (0x7fff87b50b80)
is misleading.
value is apparently NSNumber so cast it to NSNumber and then to Int64
let bilatUnilat = exercise.childSnapshot(forPath: "bilat_unilat").value as! NSNumber
cdExercise.bilat_unilat = bilatUnilat as! Int64
If the value is only 0 or 1 I recommend to declare the attribute as Bool
let bilatUnilat = exercise.childSnapshot(forPath: "bilat_unilat").value as! NSNumber
cdExercise.bilat_unilat = bilatUnilat == 1
And please name the Core Data attributes according to the naming convention lowerCamelCased

Related

can't get number from NSArrayM

i get the below error when trying to retrieve a key name from a query. and then cast it as an int of use by viewcontroller.
Could not cast value of type '__NSArrayM' (0x1073ebdb0) to 'NSNumber' (0x1069f3488).
this is the line in the query:
tempVarLDS = object.value(forKey: keyName)
when printed this returns
(
7
)
so it is an array. but i can't seem to access it via
tempvarLDS[0]
or any of the usual suspects. any idea how to get this int?
If it's an NSArray of NSNumbers, you should be able to cast it as an array of integers.
// Cast it
let tempvarLDS:[Int] = object.value(forKey: keyName) as! [Int]
// Loop
for num in tempvarLDS {
print(num)
}
I don't see why that wouldn't work

iOS Swift: Could not cast value type '__NSCFNumber' to 'NSString'

I am retrieving a number value from my Firebase database (JSON db) and then displaying this number into a textField, although I get this error when I try to display it.
Could not cast value type '__NSCFNumber' to 'NSString'
How can I properly convert the retrieved value to a String, taking into consideration that this value maybe change between a String and a Number when I retrieve it.
Here is my code:
let quantity = child.childSnapshot(forPath: "quantity").value // Get value from Firebase
// Check if the quantity exists, then add to object as string.
if (!(quantity is NSNull) && ((quantity as! String) != "")) {
newDetail.setQuantity(quantity: quantity as! String)
}
The error is saying that your quantity is Number and you cannot directly convert number to String, try like this.
newDetail.setQuantity(quantity: "\(quantity)")
Or
if let quantity = child.childSnapshot(forPath: "quantity").value as? NSNumber {
newDetail.setQuantity(quantity: quantity.stringValue)
}
else if let quantity = child.childSnapshot(forPath: "quantity").value as? String {
newDetail.setQuantity(quantity: quantity)
}
Or With Single if statement
if let quantity = child.childSnapshot(forPath: "quantity").value,
(num is NSNumber || num is String) {
newDetail.setQuantity(quantity: "\(quantity))
}
Using second and third option there is no need to check for nil.
Swift 4:
let rollNumber:String = String(format: "%#", rollNumberWhichIsANumber as! CVarArg)
You may convert your NSNumber value to string like this too, its more traditional and basic approach to format a string
newDetail.setQuantity(String(format: "%#", quantity))
Swift 4.
newDetail.setQuantity(String(describing: rollNumberWhichIsANumber))
In swift 4.1 and Xcode 9.4.1
newDetail.setQuantity(quantity: "(quantity)")
We can convert to string like this "\(quantity)"
let session_id : Int32 = (jsonObject.value(forKey: "id") as! NSNumber).int32Value
Swift 5:
I manage to fix it buy using .description when interpolating the UserDefaults value into a label converting from Int to String.
working code
highScoreLabel?.text = "HiScore: \(hiScoreValue.description)"
old code
highScoreLabel?.text = "HiScore: \(String(describing: hiScoreValue))"

Convert AnyObject to an Int

I'm trying to convert a anyObject to an Int. Here's my code:
println(currentObject[0])
println(_stdlib_getDemangledTypeName(currentObject[0]))
2
Swift.ImplicitlyUnwrappedOptional<Swift.AnyObject>
I'm trying to convert currentObject[0] to an Int. Here's what I tried:
let num: Int = currentObjec[0] as! Int
When I run the app, I get the following error:
Could not cast value of type '__NSCFString' (0x103c93c50) to 'NSNumber' (0x103535b88)
When I try this: currentObject[0].toInt()
I get an error saying
'AnyObject' does not have a member named 'toInt()'
The only way I'm able to make it work, is to do the following:
let numStr = currentObject[0] as! String
let num: Int = numStr.toInt()!
Is there a simpler way to do it? (Without having to first convert it to a String.)
From the error message
Could not cast value of type '__NSCFString' (0x103c93c50) to 'NSNumber' (0x103535b88)
you can conclude that currentObject[0] is actually an NSString.
In that case you can simply convert it with
let numStr = currentObject[0].integerValue
But note that this will crash if the array element is not an NSString.

swift forcing objective-c int to be assigned as Int32 then crashing

I have an objective c property that has been declared as
#property int xmBufferSize;
If I do sharedExample.xmBufferSize = 1024 it just works fine
but when I am trying to set an integer value for that property from another variable
var getThat:Int = dict["bufferSize"]!.integerValue
sharedExample.xmBufferSize = getThat
It can't do above
Cannot assign a value of type 'Int' to a value of type 'Int32'
If I force this to
sharedExample.xmBufferSize =dict["bufferSize"] as! Int32
It is crashing with Error
Could not cast value of type '__NSCFNumber' to 'Swift.Int32'
EDIT::::
Dict init, there are other objects in dict besides integers
var bufferSize:Int = 1024
var dict = Dictionary<String, AnyObject>() = ["bufferSize":bufferSize]
The value in dict is an NSNumber, which cannot be cast or directly converted to Int32. You can first obtain the NSNumber and then call intValue on it:
if let bufferSize = dict["bufferSize"] as? NSNumber {
sharedExample.xmlBufferSize = bufferSize.intValue
}
The if let … as? allows you to verify that the value is indeed an NSNumber, since (as you said) there can be other types of objects in dict. The then-branch will only execute if dict["bufferSize"] exists and is an NSNumber.
(Note: You can also try integerValue if intValue gives the wrong type, or convert the resulting integer – CInt(bufferSize.integerValue) – as needed. Swift doesn't do implicit conversions between different integer types, so you need to match exactly.)
You need to convert your NSNumber to Int32.
sharedExample.xmBufferSize = dict["bufferSize"]!.intValue
Use type conversion, not as:
sharedExample.xmBufferSize = Int32(dict["bufferSize"] as! Int)
That should work.

NSMutableDictionary treats NSString value as NSNumber

I have the following value in a NSMutableDictionary - see image
I'm attempting to get at "a" thus:
let a = dictionary.objectForKey("a") as! String
the app crashes at this point with
Could not cast value of type '__NSCFNumber' (0x...) to 'NSString' (0x...).
other numbers inside "" are treated as strings as are numbers outside of strings cast to String without any issue.
Can anyone let me know what's going on? And how to get at these values easily?
The value is an NSNumber, not an NSString. You can use stringValue to convert it:
if let a = d["a"] as? NSNumber {
let aString = a.stringValue
println(aString) // -1
} else {
// either d doesn't have a value for the key "a", or d does but the value is not an NSNumber
}
If you're sure it exists and is an NSNumber, you can use forced unwrapping, forced casting, and string interpolation:
let a = d["a"]! as! NSNumber
let aString = "\(a)"

Resources