从Parse.com查询数据,遍历,将某些部分添加到NSObject中,并将对象添加到对象数组中



我使用iOS7 Xcode 5与Parse.com的SDK。在通过解析查询数据时,我试图为每个返回的对象构建一个Person (NSObject),并创建一个defaultPeople的NSArray。下面是Person的代码:

Person.h

// Person.h
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) UIImage *image;
@property (nonatomic, assign) NSUInteger age;
@property (nonatomic, strong) NSString *gender;
@property (nonatomic, strong) NSString *location;
@property (nonatomic, strong) NSString *tagline;
@property (nonatomic, strong) NSString *objectId;
- (instancetype)initWithName:(NSString *)name
                       image:(UIImage *)image
                         age:(NSUInteger)age
                      gender:(NSString*)gender
                    location:(NSString*)location
                     tagline:(NSString*)tagline
                    objectId:(NSString*)objectId;
@end

Person.m:

// Person.m
#import "Person.h"
@implementation Person
#pragma mark - Object Lifecycle
- (instancetype)initWithName:(NSString *)name
                       image:(UIImage *)image
                         age:(NSUInteger)age
                      gender:(NSString*)gender
                    location:(NSString *)location
                     tagline:(NSString*)tagline
                    objectId:(NSString *)objectId {
    self = [super init];
    if (self) {
        _name = name;
        _image = image;
        _age = age;
        _gender = gender;
        _location = location;
        _tagline = tagline;
        _objectId = objectId;
    }
    return self;
}
@end

下面是我用来在视图控制器。m文件中创建数组的代码:

- (NSArray *)defaultPeople {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSLog(@"Current City for Querying: %@", [defaults objectForKey:@"CurrentCity"]);
    if ([defaults objectForKey:@"CurrentCity"]) {
    PFQuery *query = [PFQuery queryWithClassName:@"_User"];
        [query whereKey:@"CurrentCity" equalTo:[defaults objectForKey:@"CurrentCity"]];
        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
                if (!error) {
                    // The find succeeded.
                    NSLog(@"Successfully retrieved %d scores.", objects.count);
                    // Do something with the found objects
                    for (PFObject *object in objects) {
                        NSString *userID = object.objectId;
                        NSString *first = [object objectForKey:@"FirstName"];
                        NSString *city = [object objectForKey:@"CurrentCity"];
                        NSUInteger age = (int)[object objectForKey:@"Age"];
                        NSString *gender = [object objectForKey:@"Gender"];
                        NSString *tagline = [object objectForKey:@"Tagline"];
                        Person *p = [[Person alloc] 
                                            initWithName:first
                                                   image:[UIImage imageWithData:
                                                         [NSData dataWithContentsOfURL:                                                                                            
                                                         [NSURL URLWithString:
                                                         [object objectForKey:@"PictureURL"]]]]
                                                 age:age
                                              gender:gender
                                            location:city
                                             tagline:tagline
                                            objectId:userID];
                [self.people addObject:p]
                }
        } else {
            NSLog(@"Error: %@ %@", error, [error userInfo]);
            }
        }];
    }
    return self.people; //people was defined in the interface as: 
                        //@property (nonatomic, strong) NSMutableArray *people;
}

我知道查询是好的,因为我在for循环中nsloging了每个NSString/NSUInteger,它总是返回正确的值。我的问题是从这些值创建一个新的Person对象,并在每次迭代后将其添加到defaultPeople数组。这段代码的结果是我的defaultPeople数组总是返回(null)。请帮助! !谢谢:)

克莱顿

好了,伙计们,最后我弄清楚了如何在一个实际工作的块中做到这一点:

- (void)queryForAllPostsNearLocation:(CLLocation *)currentLocation withNearbyDistance:(CLLocationAccuracy)nearbyDistance {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setBool:1 forKey:@"Users"];
    PFQuery *query = [PFQuery queryWithClassName:@"_User"];
    // If no objects are loaded in memory, we look to the cache first to fill the table
    // and then subsequently do a query against the network.
    if (query.countObjects == 0) {
        query.cachePolicy = kPFCachePolicyCacheThenNetwork;
    }
    // Create a PFGeoPoint using the current location (to use in our query)
    PFGeoPoint *userLocation =
    [PFGeoPoint geoPointWithLatitude:[Global shared].LastLocation.latitude longitude:[Global shared].LastLocation.longitude];
    // Create a PFQuery asking for all wall posts 1km of the user
    [query whereKey:@"CurrentCityCoordinates" nearGeoPoint:userLocation withinKilometers:10];
    // Include the associated PFUser objects in the returned data
    [query includeKey:@"objectId"];
    //Run the query in background with completion block
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    if (error) { // The query failed
        NSLog(@"Error in geo query!");
    } else { // The query is successful
        defaultPeople = [[NSMutableArray alloc] init];
        // 1. Find new posts (those that we did not already have)
        // In this array we'll store the posts returned by the query
        NSMutableArray *people = [[NSMutableArray alloc] initWithCapacity:100];
        // Loop through all returned PFObjects
        for (PFObject *object in objects) {
            // Create an object of type Person with the PFObject
            Person *p = [[Person alloc] init];
            NSString *userID = object.objectId;
            p.objectId = userID;
            NSString *first = [object objectForKey:@"FirstName"];
            p.name = first;
            NSString *city = [object objectForKey:@"CurrentCity"];
            p.location = city;
            NSString *age = [object objectForKey:@"Age"];
            p.age = age;
            NSString *gender = [object objectForKey:@"Gender"];
            p.gender = gender;
            NSString *tagline = [object objectForKey:@"Tagline"];
            p.tagline = tagline;
            UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[object objectForKey:@"PictureURL"]]]]];
            p.image = img;
            if (![p.objectId isEqualToString:myID] && ![p.gender isEqualToString:myGender] && ![people containsObject:p]) {
                [people addObject:p];
                NSLog(@"Person: %@",p);
            }
        }
        [defaultPeople addObjectsFromArray:people];
        [[Global shared] setDefaultPeople:defaultPeople];
        NSLog(@"Default People: %@",[Global shared].defaultPeople);
        NSLog(@"Success. Retrieved %lu objects.", (unsigned long)[Global shared].defaultPeople.count);
        if (defaultPeople.count == 0) {
            [defaults setBool:0 forKey:@"Users"];
        } else {
            [defaults setBool:1 forKey:@"Users"];
            }
        }
    }];
}

底部的BOOL返回值是让控制器知道是否在提示时切换视图控制器。如果开关控制器开关被击中,它只在BOOL = 1时切换,即该区域有人。

谢谢你们的帮助。认真。

[self。people addObject:p]发生在后台线程中所以"return self。人"发生在自我之前"。人是更新的。这就是为什么它总是返回nil。

而不是[query findObjectsInBackground]NSArray *objects = [query findObjects]

您需要返回块内的人员,否则它将在完成查找对象之前击中返回语句。它与block异步查找它们

另一种方法是去掉该块并执行:

NSArray *array = [query findObjects];
for (PFObject *object in array) {
                        NSString *userID = object.objectId;
                        NSString *first = [object objectForKey:@"FirstName"];
                        NSString *city = [object objectForKey:@"CurrentCity"];
                        NSUInteger age = (int)[object objectForKey:@"Age"];
                        NSString *gender = [object objectForKey:@"Gender"];
                        NSString *tagline = [object objectForKey:@"Tagline"];
                        Person *p = [[Person alloc] 
                                            initWithName:first
                                                   image:[UIImage imageWithData:
                                                         [NSData dataWithContentsOfURL:                                                                                            
                                                         [NSURL URLWithString:
                                                         [object objectForKey:@"PictureURL"]]]]
                                                 age:age
                                              gender:gender
                                            location:city
                                             tagline:tagline
                                            objectId:userID];
                [self.people addObject:p];
}
return self.people;

最新更新