我不明白为什么我的NSMutuableArray为空?我错过了什么吗?我在解析中存储了一个字符串。 感谢您的帮助。
.h file
@interface IncomeTransactionViewController : UIViewController <UIPickerViewDataSource, UIPickerViewDelegate>
{
NSDate *myDate;
NSMutableArray *accountArray;
UIPickerView *accountPicker;
}
@property (weak, nonatomic) IBOutlet UITextField *dateField;
@property (weak, nonatomic) IBOutlet UITextField *accountField;
@property (weak, nonatomic) IBOutlet UITextField *categoryField;
- (IBAction)hidekeyboard:(id)sender;
- (IBAction)addTransaction:(id)sender;
@end
.m file
PFQuery *query = [PFQuery queryWithClassName:@"Account"];
[query whereKey:@"user" equalTo:[PFUser currentUser]];
[query orderByDescending:@"startingBalance"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
accountArray = [[NSMutableArray alloc]init];
for (PFObject *object in objects) {
[accountArray addObject:object[@"name"]];
NSLog(@"%@", object[@"name"]);
}
}
];
答案 0 :(得分:0)
如果在启动查询后立即检查accountsArray,则它将为nil,因为查询是异步的,并且在完成之前不会调用其回调。
如果这是您的代码:
PFQuery *query = [PFQuery queryWithClassName:@"Account"];
[query whereKey:@"user" equalTo:[PFUser currentUser]];
[query orderByDescending:@"startingBalance"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
accountArray = [[NSMutableArray alloc]init];
for (PFObject *object in objects) {
[accountArray addObject:object[@"name"]];
NSLog(@"%@", object[@"name"]);
}
}];
int ct = [accountArray count];
然后ct将为0并且accountArray将为nil,但是当调用回调时,将分配并填充accountArray。之前提到的正确答案,我将在这里用更好的解释进行迭代,是在viewDidLoad中分配数组。或者,您可以在查询调用之前分配它:
accountArray = [[NSMutableArray alloc]init];
PFQuery *query = [PFQuery queryWithClassName:@"Account"];
[query whereKey:@"user" equalTo:[PFUser currentUser]];
[query orderByDescending:@"startingBalance"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
for (PFObject *object in objects) {
[accountArray addObject:object[@"name"]];
NSLog(@"%@", object[@"name"]);
}
}];
int ct = [accountArray count];
或者您可以执行块内部数组所需的任何操作:
accountArray = [[NSMutableArray alloc]init];
PFQuery *query = [PFQuery queryWithClassName:@"Account"];
[query whereKey:@"user" equalTo:[PFUser currentUser]];
[query orderByDescending:@"startingBalance"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
for (PFObject *object in objects) {
[accountArray addObject:object[@"name"]];
NSLog(@"%@", object[@"name"]);
}
int ct = [accountArray count];
NSLog(@"Array countents: %@", accountArray);
}];