2013-06-19 54 views
0

我試圖在下面的代碼中設置一個屬性值,但是當我退出該屬性值爲空時。塊完成後未設置屬性值

- (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); 
} 

我做錯了什麼?

+0

你做了什麼調試/記錄? – Wain

+0

只需在代碼底部的NSLog行。 – pedroremedios

+0

因此,找出'JSON'中的內容以及'response'是否有效...... – Wain

回答

-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]; 
+0

我已經說了。仍然不起作用。 – pedroremedios