set value of UISlider with a variable - ios

I have now spent about 12 hours trying to solve this riddle, but I just can't! The truth is I am about 3 weeks into my Swift adventure and this is the first time I have ever written any code (well I think I made a rainbow once on my Atari 800XL!)
I don't really know what I am doing.... I also understand that what I am trying to do here could be fundamentally wrong, and so I will appreciate gift wrapped criticism.
I have a slider - C1
I want to set its value with a variable. However, it wants a float and I can't seem to convert the array I am using to a float. In fact I can't get any of the array values to convert to anything else, and keep getting an error about AnyObject. The code below is one iteration of the trials i have run, all without any luck. It is driving me mad!
The errors are
can't assign a value of int to a value of type float
AnyObject is not convertible to NSNumber; did you mean to use as! to force downcast
This is the code where I get the array from Parse and assign it to NSUSER.
var defaults = NSUserDefaults.standardUserDefaults()
var getAuditId:String = defaults.stringForKey("auditIdGlobal")!
var userId:String = defaults.stringForKey("userIdGlobal")!
var query = PFQuery(className: "auditData")
query.whereKey("auditId", equalTo:getAuditId)
query.findObjectsInBackgroundWithBlock {
(objects: Array?, idError: NSError?) -> Void in
if idError == nil {
if let objects = objects as? [PFObject] {
for object in objects {
var auditId: AnyObject? = object["auditId"]!
var callEhs: AnyObject? = object["ehsData"]!
NSUserDefaults.standardUserDefaults().setObject(callEhs, forKey: "ehsLoad")
This is the code at the user end
var defaults = NSUserDefaults.standardUserDefaults()
var loadArray = defaults.arrayForKey("ehsLoad")!
var test: AnyObject = loadArray[0]
var testFloat = Int(test)
c1.value = testFloat
I appreciate that it shows an int above, but I can't convert to anything!
Xcode asked me to insert a forced downcast to as!NSNumber
var = int(test as! NSNumber)
here I get this error
Could not cast value of type '__NSCFString' (0x10c0bfc50) to 'NSNumber' (0x10c550b88).
(lldb)
if I try to use a forced downcast
var testFloat = test as! Float
On running the app i get the error
Could not cast value of type '__NSCFString' (0x10b690c50) to 'NSNumber' (0x10bb21b88).
(lldb)

Your test variable is a NSString. Try
var test = loadArray[0] as! NSString
and then use
test.floatValue

Related

Core Data and making double from type AnyObject? Swift

I was writing a code for CoreData. My datamodel includes name and moneyAmount. Here's the part of the code I have troubles with
do {
let request = NSFetchRequest(entityName: "MoneyData")
let results = try context.executeFetchRequest(request)
if results.count > 0 {
for item in results as! [NSManagedObject] {
let name = String(item.valueForKey("name"))
let moneyAmount = item.valueForKey("moneyAmount")
moneyManager.addMoney(name, moneyAmount: moneyAmount)
}
}
} catch {
print("There was an error saving data")
}
Now the problem is that my moneyManager.addMoney requires String and Double. However, with this code, the error that I get is:
Optional Chain has no effect, already produces 'Anyobject?'
Cannot convert value of type AnyObject? to expected argument type 'Double'
I don't really understand what it means by Anyobject. I think I should convert anyobject to double to make it work right?
Thanks in advance
valueForKey() returns an object of type AnyObject because there's no way of knowing at compile-time what type of object it's referencing. You can cast to a specific type using as. For example, moneyAmount as? Double will result in an object of type Double?, either containing the numeric value, or being nil if the object wasn't of type Double.

Swift realm.io can get object property using object.getValueForKey("key") but not as object.key

I am trying since a whole day migrating my localStorage data to realm.io...
Now the only issue I am facing is that I can get the object property using
object.valueforKey("key")
but not using the simpler one
object.key
Here you have a peace of my code
let realm = try! Realm()
let predicate = NSPredicate(format: "groupID = %#", group.valueForKey("groupID") as! String )
let current = realm.objects(apiGroup).filter(predicate)
let currentGroup = current[0]
print(currentGroup.valueForKey("token") as! String)
print(currentGroup.token)
When I execute that this is been printed on the console.
56abbf408cfea7941a8b30b7
fatal error: unexpectedly found nil while unwrapping an Optional value
Can you please tell me if this is the normal behaviour or if I can do something to get the
"object.key"
notation??
Thanks in advance
Thanks all for your views. I ended up creating a custom object with a custom init and passing realm object to it...
Then I looped the realm object to assign the same object properties to the custom one... example
class Images:Object{
var picid:String = ""
var path:String = ""
var timeStamp:NSDate!
override class func primaryKey() -> String{
return "picid"
}
}
class realmImages{
var picid:String!
var path:String!
var timeStamp:NSDate!
init(object:Images){
picid = object.valueForKey("picid") as! String
path = object.valueForKey("path") as! String
timeStamp = object.valueForKey("timeStamp") as! NSDate
}
}
Hang on! I think I didn't actually understand the question properly!
If the .token property is actually a member of your class, that should absolutely work. Just to confirm, are you defining your members of your Realm model subclass properly, according to the documentation?
class APIGroup: Object {
dynamic var token = ""
}
If so, and you're STILL having trouble, it may be possible that Swift wasn't able to infer that the type of the object returned from the filter wasn't your APIGroup object (Which would explain why valueForKey still works).
If that's the case, stating the type should help:
let currentGroup = current[0] as APIGroup
Let me know if that helped!

Pointers in Parse (ios)

I am trying to access an instance of a class via a pointer "Parent", and I believe I have everything right, except I have an error. The error states "Use of unresolved identifier 'object'". What am I doing wrong here?
var parentObjectId: String = String()
var query1 = PFQuery(className: "ComparablePhotos")
query1.includeKey("Parent")
if let pointer = object["Parent"] as? PFObject {
parentObjectId = object["objectId"] as! String!
}
println(parentObjectId)
You aren't actually running the query to get back the object, or more likely array of objects, which you can then access the properties of.

How do I get Parse data as a String out of PFUser?

I am currently trying to get a value called "loot" out of the current user. I need the value as a String, but Swift is being stubborn and says it "cannot convert Anyobject to String". The Parse documentation for iOS says to use something like:
let score = gameScore["score"] as String
and so, I try this :
let lootAmount = user["loot"] as String
BTW 'user' is referring to the current user. When I try that, it gives error saying it's not convertible. I tried placing '!'s and '?'s wherever Xcode suggested, but it just crashed the app with no error.
So, how do I get the user value called "loot" as a String?
Loot is an NSNumber not an NSString or String.
You could convert it to a String like this:
if let loot = user["loot"] as? NSNumber {
let lootString = "\(loot)"
}
If you're not sure of an object's type, you can ask it using dynamicType:
print(user["loot"]!.dynamicType)
//prints `__NSCFNumber.Type`
You may need to downcast AnyObject. Try this: let lootAmount = user["loot"] as? String or unwrap your optional user if you haven't done so:
let currentUser = PFUser.currentUser()
if let user = currentUser {
let lootAmount = user["loot"] as String
}

Swift AnyObject as String dynamic cast failed

I have an Int that I saved in Parse as an AnyObject. When I retrieve the AnyObject? and try to cast it as a String, NSString, NSNumber, or anything else, I keep getting an EXC_Breakpoint as the casting is returning Nil and there's a "Swift dynamic cast failed" error".
I tried to create this simple test to figure out which part fails, but the crazy thing is that this test will pass where seemingly all the steps are the same:
func testAnyObjectCasting(){
var myInt32: Int32 = 265
var myInt: Int = Int(myInt32)
var myAnyObject: AnyObject? = myInt as AnyObject
var myAnyArray: [[AnyObject]] = [[AnyObject]]()
myAnyArray.append(["something", myAnyObject!])
println(myAnyObject)
var myOtherAnyObject: AnyObject? = myAnyArray[0][1]
println(myOtherAnyObject)
var myString:NSNumber? = myOtherAnyObject as? NSNumber
println(myString)
var myInt2: Int = myString! as Int
}
Here's the relevant code snippets from my logic, and notes that println() works fine until the downcast to NSNumber, at which time Nil is returned:
//ABRecordGetRecordId returns an ABRecordID, which is of type Int32
//This value that's stored in the 2nd column of the multiDim [[AnyObject]]
var personId: Int = Int(ABRecordGetRecordID(person))
//This is a call to a Parse object, which returns an AnyObject. I then cast that to
//a multidimensional array AnyObject as that's the true structure of the data in swift speak
var deviceContacts: [[AnyObject]] = device?[deviceContactsFieldName] as [[AnyObject]]
//This returns the expected value, which in my broader test case is 99999, which is supported by Int
var i:Int = 1
println("the value in device contacts \(i) column 1 is: \(deviceContacts[i][1])")
//This takes a single cell value from the multidim array and puts it in an optional AnyObject
var valueInParse: AnyObject? = deviceContacts[i][1]
//This still returns 99999
println(valueInParse)
//This is where 99999 is replaced with nil. Any ideas?
var valueNSNumberInParse: NSNumber? = valueInParse as? NSNumber
//Nil :(
println(valueNSNumberInParse)
//Exception as I'm trying to unwrap nil :(
var unwrappedNSNumber:NSNumber = valueNSNumberInParse!
Part of my frustration is that I don't understand why println() works fine for AnyObject but all the casting fails. Clearly there's code that can interpret the value as a string to show for println, but that syntax eludes me for proper casting.
Because you have saved an Int into Parse and an Int is not an object it had to be converted to an object. It seems that the Parse framework has converted it to an NSValue, which is effectively a byte buffer that represents an intrinsic type.
You could try and convert these bytes back to an Int, but it is easier and better to encode the value into an NSNumber before storing it in the Parse object - then you will be easily able to handle it when you retrieve the object.

Resources