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

时间:2015-04-14 19:06:15

标签: 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传递给我的下一个视图控制器,它是一个swift视图控制器。从研究来看,似乎人们建议为segue做准备。如何让我的变量存在于这个新函数中?下面是我尝试过的,但经过调试后,在我的函数执行之前创建视图时,实际上会出现prepareForSegue。所有准备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;
    }
}

1 个答案:

答案 0 :(得分:1)

您需要在success块中调用performSegue,因为该方法是异步的。你现在拥有它的方式,在成功块运行之前调用performSegue,因此userID将为nil。 userID也是一个局部变量,所以为了使它在prepareForSegue方法中可用,在performSegueWithIdentifier:sender:。中传递userID而不是self作为sender参数。