Pointers in Parse (ios) - 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.

Related

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!

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
}

set value of UISlider with a variable

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

Cannot subscript a value of [AnyObject]? with an index of type Int

This is in a class extending PFQueryTableViewController and I am getting the following error. The rows will be PFUser only.
Why am I not able to cast it? Is there a way around this?
The error is:
Cannot subscript a value of [AnyObject]? with an index of type Int
...for this line:
var user2 = self.objects[indexPath.row] as! PFUser
The problem isn't the cast, but the fact that self.objects seems to be an optional array: [AnyObject]?. Therefore, if you want to access one of its values via a subscript, you have to unwrap the array first:
var user2: PFUser
if let userObject = self.objects?[indexPath.row] {
user2 = userObject as! PFUser
} else {
// Handle the case of `self.objects` being `nil`.
}
The expression self.objects?[indexPath.row] uses optional chaining to first unwrap self.objects, and then call its subscript.
As of Swift 2, you could also use the guard statement:
var user2: PFUser
guard let userObject = self.objects?[indexPath.row] else {
// Handle the case of `self.objects` being `nil` and exit the current scope.
}
user2 = userObject as! PFUser
I ran into the same issue and resolved it like this:
let scope : String = searchBar.scopeButtonTitles![searchBar.selectedScopeButtonIndex] as! String
For your case, you might do:
var user2 : PFUser = self.objects![indexPath.row] as! PFUser
My workaround would be..
If you are certain that the tableview will contain only users try to typecast the objects Array of AnyObject to Array of PFUser. then use it.
Just add an ! (exclamation mark) after objects, like so:
var user2 = self.objects![indexPath.row] as! PFUser
That fixed it for me :)
I had a similar issue with the following line:
array![row]
I could not understand where the issue came from; if I replaced row with a number like 1 the code compiled and ran without any issues.
Then I had the happy thought of changing it to this:
array![Int(row)]
And it worked. For the life of me, I don't understand why giving an array an index of -1is theoretically legal, but there you go. It makes sense to me for subscripts to be unsigned, but maybe it's just me; I'll have to ask Chris about it.

Why is array empty after appending object to it

I am working in a TableViewController that I am trying to fill up with data from a plist.
I declared this at the top:
var studentsArray:Array<StudentData>?
And now I am doing the following in a function that loads my plist:
var path = NSBundle.mainBundle().URLForResource("students", withExtension: "plist")
let tmpArray = NSArray(contentsOfURL: path!)
for studentDict in tmpArray!{
let name = studentDict["name"]as! String
let dateOfBirth = studentDict["dateOfBirth"] as! NSDate
let regular = studentDict["regular"] as! Bool
let photoFileName = studentDict["photoFileName"] as! String
let data = StudentData(name : name, dateOfBirth: dateOfBirth, regular : regular, photoFileName: photoFileName)
self.studentsArray?.append(data)
println(studentsArray!.count)
}
I tried logging the properties of the Object, they are all being filled in, but it goes wrong at the .append and somehow it just won't do that. The array's count remains 'Nil' when logged.
I'm kind of lost here! Any help is appreciated.
Doesn't look like you are initializing studentsArray anywhere. Make sure to do that. For the record, array.count should be 0 if the array is empty, not nil. If you are seeing nil that means the array is probably nil (aka you didnt initialize it).
Try changing your array declaration to this and let me know if it works. Hope it helps:
var studentsArray:Array<StudentData>? = Array<StudentData>()

Resources