如何在块内设置 属性 (Firebase)
How to set property inside a block (Firebase)
我想在块中设置 属性 "users",但在块函数之外 属性 产生 nil。
@property (strong, nonatomic) NSMutableArray *users;
- (void)configureData {
_ref = [[FIRDatabase database] reference];
FIRUser *user = [FIRAuth auth].currentUser;
NSString *currentUserID = user.uid;
_refHandle = [[[[_ref child:@"users"] queryOrderedByChild:[NSString stringWithFormat:@"appliedByUsers/%@", user.uid]] queryEqualToValue:@YES] observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
_users = [[NSMutableArray alloc] init];
for (FIRDataSnapshot *user in snapshot.children) {
[_users addObject:user.key];
NSLog(@"first object in userArray: %@", users[0]);
}
}];
NSLog(@"first object in userArray outside block: %@", users[0]);
}
在块内修改 属性 的最佳做法是什么?
_refHandle = [[[[_ref child:@"users"] queryOrderedByChild:[NSString stringWithFormat:@"appliedByUsers/%@", user.uid]]
queryEqualToValue:@YES] observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
_users = [[NSMutableArray alloc] init];
for (FIRDataSnapshot *user in snapshot.children) {
[_users addObject:user.key];
NSLog(@"first object in userArray: %@", users[0]);
}
}];
这段代码只是为块参数设置了一个值。你知道代码块什么时候执行吗?你发现user[0] = nil,因为在前面执行日志代码时,没有执行块代码。
我想在块中设置 属性 "users",但在块函数之外 属性 产生 nil。
@property (strong, nonatomic) NSMutableArray *users;
- (void)configureData {
_ref = [[FIRDatabase database] reference];
FIRUser *user = [FIRAuth auth].currentUser;
NSString *currentUserID = user.uid;
_refHandle = [[[[_ref child:@"users"] queryOrderedByChild:[NSString stringWithFormat:@"appliedByUsers/%@", user.uid]] queryEqualToValue:@YES] observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
_users = [[NSMutableArray alloc] init];
for (FIRDataSnapshot *user in snapshot.children) {
[_users addObject:user.key];
NSLog(@"first object in userArray: %@", users[0]);
}
}];
NSLog(@"first object in userArray outside block: %@", users[0]);
}
在块内修改 属性 的最佳做法是什么?
_refHandle = [[[[_ref child:@"users"] queryOrderedByChild:[NSString stringWithFormat:@"appliedByUsers/%@", user.uid]]
queryEqualToValue:@YES] observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
_users = [[NSMutableArray alloc] init];
for (FIRDataSnapshot *user in snapshot.children) {
[_users addObject:user.key];
NSLog(@"first object in userArray: %@", users[0]);
}
}];
这段代码只是为块参数设置了一个值。你知道代码块什么时候执行吗?你发现user[0] = nil,因为在前面执行日志代码时,没有执行块代码。