问题
I'm trying to use a value generated inside of a block ("fid") outside of a block. The problem being that the value is being pulled before the block has run, and so the value returns as (null), even though the data is present. Does anyone know how I can make this work? See code:
.h
@property (nonatomic, strong) NSString *fid;
.m
[DIOSFile fileSave:file success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"File uploaded!");
[file setObject:[responseObject objectForKey:@"fid"] forKey:@"fid"];
[file removeObjectForKey:@"file"];
fid = [responseObject objectForKey:@"fid"];
NSLog(@"%@",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Failed to upload file!");
}];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject: [NSString stringWithFormat:@"%@", fid] forKey:@"fid"];
NSLog(@"%@", fid);
NSDictionary *fidLangDict = [NSDictionary dictionaryWithObject:[NSArray arrayWithObject:dict] forKey:@"und"];
[nodeData setObject:fidLangDict forKey:@"field_photo"];
回答1:
Move the code inside the block
[DIOSFile fileSave:file success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"File uploaded!");
[file setObject:[responseObject objectForKey:@"fid"] forKey:@"fid"];
[file removeObjectForKey:@"file"];
fid = [responseObject objectForKey:@"fid"];
NSLog(@"%@",responseObject);
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject: [NSString stringWithFormat:@"%@", fid] forKey:@"fid"];
NSLog(@"%@", fid);
NSDictionary *fidLangDict = [NSDictionary dictionaryWithObject:[NSArray arrayWithObject:dict] forKey:@"und"];
[nodeData setObject:fidLangDict forKey:@"field_photo"];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Failed to upload file!");
}];
回答2:
There are two ways you can do this:
Move the code outside completion block into success block which you want to execute after success.
Create a method and pass responseObject as parameter to it. Onsuccess call this method with responseObject as parameter. Dont do anything below completion block of request
Let me know if you need any help
来源:https://stackoverflow.com/questions/29926504/nsstring-value-returning-before-block-has-run