块完成后未设置属性值

时间:2013-06-19 07:59:00

标签: objective-c objective-c-blocks

我正在尝试在以下代码中设置属性值,但是当块退出时,该属性值为null。

- (PRSapoAuth *)initWithUser:(NSString *)user password:(NSString *)password forToken:{

__block NSString *token;

self = [super init];
if (!self) {
    return nil;
}

NSString *urlAuth = [NSString stringWithFormat:@"https://services.sapo.pt/Codebits/gettoken?user=%@&password=%@", user, password];
NSString *modifiedURL = [urlAuth stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:modifiedURL]];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
    token = JSON[@"token"];
    self.token = token;
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
    token = @"";
    self.token = token;
}];
[operation addObserver:self forKeyPath:@"isFinished" options:NSKeyValueObservingOptionNew context:nil];
[operation start];
while (!operation.isFinished) {
}

return self;

}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
NSLog(@"%@", self.token);
}

我做错了什么?

1 个答案:

答案 0 :(得分:-1)

you need to call method in this order.Not sure but will work for you 


   [operation start];
    [operation addObserver:self forKeyPath:@"isFinished" options:NSKeyValueObservingOptionNew context:nil];