Segue不会传递数据

时间:2013-11-17 20:01:58

标签: ios objective-c uiviewcontroller segue

所以我从一个UIViewController设置了一个segue到另一个(MenuViewController到AgendaViewController),但是目标UIViewController上的变量仍显示为null,即使我在segue期间更新了它。

我在segue方法中做错了吗?

这是MenuViewController的代码,我正试图阻止它的视图:

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if([segue.identifier isEqualToString:@"toAgenda"]){
    AgendaViewController *controller = (AgendaViewController *)segue.destinationViewController;

    // Load agenda url based on event's name
    PFQuery *event_query = [PFQuery queryWithClassName:@"Event"];
    [event_query whereKey:@"event_name" equalTo:event_name];
    [event_query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            for (PFObject *object in objects) {
                controller.agenda_url = (NSString*)[object objectForKey:@"event_agenda_url"];
                NSLog(@"%@", [object objectForKey:@"event_agenda_url"]);
            }
        } else {
            NSLog(@"Error: %@ %@", error, [error userInfo]);
        }
    }];
    }
}

这是我对目标视图控制器的代码,AgendaViewController:

#import "AgendaViewController.h"
#import "Parse/Parse.h"

@interface AgendaViewController ()

@end

@implementation AgendaViewController

@synthesize agenda_url;
@synthesize webView;

- (void)viewDidLoad
{
[super viewDidLoad];

// Load web view with agenda url, which was just retrieved
NSURL *url =[NSURL URLWithString:agenda_url];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
[webView loadRequest:request];

NSLog(@"Data recieved. Agenda_url = %@", agenda_url);
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) { }
return self;
}

@end

谢谢!

1 个答案:

答案 0 :(得分:1)

对我来说,它看起来像是null,因为你在第二个线程上分配了agenda_url值。所以基本上在执行viewdidload的完成块之前触发了AgendaViewController findObjectsInBackgroundWithBlock:方法。要解决此问题,您应该在主线程上分配agenda_url或在完成块中调用loadRequest:

 [event_query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    if (!error) {
        for (PFObject *object in objects) {
            controller.agenda_url = (NSString*)[object objectForKey:@"event_agenda_url"];
            NSLog(@"%@", [object objectForKey:@"event_agenda_url"]);
        }
        NSURL *url =[NSURL URLWithString:controller.agenda_url];
        NSURLRequest *request=[NSURLRequest requestWithURL:url];
        [controller.webView performSelectorOnMainThread:@selector(loadRequest:) withObject:request waitUntilDone:NO];
    } else {
        NSLog(@"Error: %@ %@", error, [error userInfo]);
    }
}];

刚刚编辑了上面的代码,在主线程上执行loadRequest。正如下面的评论所示,在后台线程上调用UIKit元素是不安全的。