ios - 使用存在于另一个函数中的 prepareForSegue 传递变量

标签 ios objective-c swift

我有这个功能:

- (void)requestMeWithToken:(NSString *)accessToken {
    [self.client GET:[NSString stringWithFormat:@"https://api.linkedin.com/v1/people/~?oauth2_access_token=%@&format=json", accessToken]
          parameters:nil
             success:^(AFHTTPRequestOperation *operation, NSDictionary *result)
    {
        NSLog(@"The current user is:%@", result);

        NSMutableDictionary *newResult = [result mutableCopy]; //copies the NSDictionary 'result' to a NSMutableDictionary called 'newResult'

        [newResult setObject: [newResult objectForKey: @"id"] forKey: @"AppUserID"]; //copies the value assigned to key 'id', to 'AppUserID' so the database can recognize it
        [newResult removeObjectForKey: @"id"]; //removes 'id' key and value
        NSString *userID = [newResult objectForKey: @"AppUserID"]; //pulls the AppUserID out as a NSString called 'userID'

        LinkedInLoginJSON *instance= [LinkedInLoginJSON new]; //calls LinkedInPost method from LinkedInLoginJSON controller
        [instance LinkedInPost:newResult];

        [self performSegueWithIdentifier:@"toHotTopics" sender: self];  

    }
     failure:^(AFHTTPRequestOperation *operation, NSError *error)
    {
        NSLog(@"failed to fetch current user %@", error);
    }
];

}

使用这段代码,我需要将带有此 segue 的 userid 传递给我的下一个 View Controller ,它是一个 swift View Controller 。从研究来看,人们似乎建议为 segue 做准备。如何让我的变量存在于这个新函数中?下面是我尝试过的,但在调试之后,似乎 prepareForSegue 实际上是在我的函数执行之前创建 View 时发生的。我可以在网上找到的所有 prepare for segue 示例都只是在范围内声明并传递一个变量。有没有办法在我的第一个函数中创建某种类型的自定义 prepareForSegue?或者我可以在第一个函数中创建变量后以某种方式将它传递给第二个函数吗?

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)userID{
    if ([[segue identifier] isEqualToString: @"toHotTopics"]) {
        //create the swift file and set the property I want to pass here
        TrendingPollsController *vc = (TrendingPollsController *)segue.destinationViewController;
        //vc.teststring = blank string in my swift file

        vc.teststring = userID;
    }
}

最佳答案

您需要从成功 block 中调用 performSegue,因为该方法是异步的。按照您现在的方式,performSegue 在成功 block 运行之前被调用,因此 userID 将为 nil。 userID 也是一个局部变量,因此要使其在 prepareForSegue 方法中可用,请将 userID 而不是 self 作为 performSegueWithIdentifier:sender: 中的 sender 参数传递。

关于ios - 使用存在于另一个函数中的 prepareForSegue 传递变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29635451/

相关文章:

ios - RxSwift MVVM 实现查询

iphone - 尝试将 plist 文件保存到设备目录

ios - 将 50 个文件夹的数据集添加到 iOS 应用程序的最佳方法是什么?

ios - 我的应用从 ios 6.0 切换到 5.0 时应该注意什么?

objective-c - 在这种情况下是否需要 dispatch_async(dispatch_get_main_queue(), ...) ?

Swift tableView 单元格没有 webView 成员

arrays - 尝试使数组中的特定索引不再是数组类型

ios - UIButtonTypeDetailDisclosure 颜色变化

IOS Collection View 布局问题

ios - 容器 View - 没有导出可能