1

I'm trying to build a simple App where users can choose a video from a tableViewController, which then loads a view that plays a video. My problem is transferring the URL of the video from the tableViewController to the viewController.

I followed this tutorial, and I am now trying to adapt the code to play videos instead of just show images

I am creating a viewController from a tableViewController like this:

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    wwfpViewController * DVC = [[wwfpViewController alloc] init];
    NSIndexPath * path = [self.tableView indexPathForSelectedRow];
    NSString * theVideoName = [videoNames objectAtIndex:path.row];
    NSString * theVideoURL = [videoList objectAtIndex:path.row];
    DVC.videoNum = path.row;
    DVC.videoName = theVideoName;
    DVC.videoURL = theVideoURL;
    [DVC play];
}

The play message for this viewController is then fired, and when I NSLog from this message the videoURL is present and correct.

Then viewDidLoad is fired on this viewController, and at this point when I NSLog the videoURL it is returned as (null).

I'm declaring the videoURL like this:

@property (strong, nonatomic) NSString * videoURL;

So I have a few questions:

  • Does a viewController lose its properties when viewDidLoad is fired?
  • Is there a better approach to sending properties to a viewController?
  • Am I doing this completely wrong?
  • And do I need to provide any more code?
4

2 回答 2

4

问题在于,尽管您使用的是 segue,但您手动分配/初始化控制器并设置其属性(当然,这与将要呈现的实例完全不同)。

这是您应该做的:

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Grab the destination controller
    // (it will be instantiated from the Storyboard automatically)
    wwfpViewController * DVC = (wwfpViewController *)segue.destinationViewController;
    NSIndexPath * path = [self.tableView indexPathForSelectedRow];
    NSString * theVideoName = [videoNames objectAtIndex:path.row];
    NSString * theVideoURL = [videoList objectAtIndex:path.row];
    // Set the properties
    DVC.videoNum = path.row;
    DVC.videoName = theVideoName;
    DVC.videoURL = theVideoURL;
    [DVC play]; // Why don't you call this on viewDidLoad of the destination controller?
}

PS:在 Objective-C 中,您通常命名 ivars(按照惯例),以便它们以小写字母开头,而 Classes 则以大写字母开头。因此WWFPViewControllerdvc在您的情况下,这将是更合适的名称。

于 2013-06-14T09:57:05.373 回答
1

您错误地初始化和配置了新的控制器实例,该实例在- (void)prepareForSegue:方法结束后被释放并且从未实际使用过。另一个控制器实例由 segue 自动初始化,然后呈现。这就是您看到“null”的原因,它没有真正配置。

如果您使用 segue,则必须配置UIStoryboardSegue实例提供的目标视图控制器,而不是创建新的。

像这样的东西:

wwfpViewController * DVC = (wwfpViewController *)segue.destinationViewController;
于 2013-06-14T09:58:27.350 回答