Value of NSString returns null, but unsure why?

…衆ロ難τιáo~ 提交于 2020-01-06 13:52:35

问题


I've set the value of my NSString called "fid" to responseObject (see below). responseObject returns the data I want when NSLog'd, but for some reason when I NSLog fid further down, it's empty. Am I missing something? See code:

.h

@property (nonatomic, assign) 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!");
  }];

    NSDictionary *bodyValues = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:_itemDescrip.text, nil] forKeys:[NSArray arrayWithObjects:@"value", nil]];
    NSDictionary *languageDict = [NSDictionary dictionaryWithObject:[NSArray arrayWithObject:bodyValues] forKey:@"und"];
    [nodeData setObject:languageDict forKey:@"body"];

    [nodeData setObject:@"storage_item" forKey:@"type"];

    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"];

    [DIOSNode nodeSave:nodeData success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Node saved!");


    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Node did not save!");
    }];

回答1:


You are calling an asynchronous method.

The log statement "further down" is executed long before the fileSave method is completed. The two callbacks of fileSave will be called sometime in the distant future (could be many seconds from now).

Whatever you want to do that needs fid must be done in the completion block of fileSave.



来源:https://stackoverflow.com/questions/29900620/value-of-nsstring-returns-null-but-unsure-why

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