NSString value returning before Block has run

旧巷老猫 提交于 2020-01-05 18:37:10

问题


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:

  1. Move the code outside completion block into success block which you want to execute after success.

  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!