我使用的是带有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)