Setting PFObject in to UILabel

2019-08-19 06:17发布

问题:

I have created a PFObject named UserInfo. Everything saves to Parse correctly, but when I go to retrieve it I keep getting errors. Here is my code below.

PFQuery *query = [PFQuery queryWithClassName:@"UserInfo"];
[query whereKey:@"user" equalTo:currentUser];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    if (error) {
        NSLog(@"Error: %@ %@", error, [error userInfo]);
    } else {
        self.userInfo = objects;
        NSLog(@"%@", self.userInfo);

        self.locationDisplay.text = [self.userInfo valueForKey:@"location"];

    }
}];

The NSLog out put for the error is as follows:

-[__NSArrayI length]: unrecognized selector sent to instance 0x9aa2be0 

Thank you for the help in advance!

回答1:

The query findObjectsInBackgroundWithBLock: stores an array in objects.

Once this is done, you set your attribute userInfo to point to this array with the line

self.userInfo = objects;

So basically here, self.userInfo holds a reference to an array.

When you try to set your label, you call the method valueForKey: directly on the array. I believe you want to call this method on an object inside this array.

What you could try is change the line to :

self.locationDisplay.text = [[self.userInfo firstObject] valueForKey:@"location"];

which will look for the value for the key @"location" on the first object of your array, which should be a PFObject.

Note : you should first test that objects is not an empty array before calling this line, otherwise you may try to call valueForKey: on a nil object, if the array is empty.