代码之家  ›  专栏  ›  技术社区  ›  rockandride

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

  •  0
  • rockandride  · 技术社区  · 10 年前

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

    人.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
    

    人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
    

    下面是我用来尝试在viewcontroller.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循环中对每个NSString/NSUInteger进行了NSLogged,它总是返回正确的值。我的问题是从这些值创建一个新的Person对象,并在每次迭代后将其添加到defaultPeople数组中。这段代码的结果是,我的defaultPeople数组始终返回(null)。请帮忙!!!谢谢:)

    克莱顿(Clayton)

    3 回复  |  直到 10 年前
        1
  •  1
  •   rockandride    10 年前

    好了,伙计们,最后我想好了如何在一个实际可行的街区里做到这一点:

    - (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(即该区域有人)时切换。

    谢谢你所有的帮助。认真地

        2
  •  0
  •   Subash    10 年前

    [self.people addObject:p]在后台线程中发生,因此“return self.peoples”在self.pepeople更新之前发生。这就是为什么它总是返回零。

    代替[query findObjectsInBackground],您可以 NSArray*objects=[query findObjects]

        3
  •  0
  •   Jacob    10 年前

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

    另一种选择是摆脱障碍,并做到:

    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;