【发布时间】:2014-08-06 21:16:32
【问题描述】:
我正在使用带有 Parse.com 的 SDK 的 iOS7 Xcode 5。在通过解析查询数据时,我试图为每个返回的对象构造一个人(NSObject)并创建一个 defaultPeople 的 NSArray。 这是 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 循环中对每个 NSString/NSUInteger 进行了 NSLogged,它总是返回正确的值。我的问题是从这些值创建一个新的 Person 对象,并在每次迭代后将其添加到 defaultPeople 数组中。此代码的结果是我的 defaultPeople 数组始终返回 (null)。请帮忙!!!谢谢:)
克莱顿
【问题讨论】:
-
您在代码中的哪个位置将新的 Person 对象添加到数组中?
-
@Jacob - 将其编辑到我拥有它的位置,看看。非常感谢。
标签: for-loop ios7 nsarray parse-platform nsobject