正如其他人所说,一般的想法是在 FirstViewController 上有一个属性来存储它需要加载的 URL,然后在视图出现时将该 URL 加载到 UIWebView 中。
这是一个从标题开始的示例:
@interface FirstViewController : UIViewController {
UIWebView *webView;
NSURL *storyURL;
}
@property (nonatomic, retain) IBOutlet UIWebView *webView; // this is set up in your nib
@property (nonatomic, retain) NSURL *storyURL;
@end
现在进行实施:
@implementation FirstViewController
@synthesize webView;
@synthesize storyURL;
- (void)dealloc;
{
[storyURL release]; // don't forget to release this
[super dealloc];
}
- (void)viewDidAppear:(BOOL)animated;
{
// when the view appears, create a URL request from the storyURL
// and load it into the web view
NSURLRequest *request = [NSURLRequest requestWithURL:self.storyURL];
[self.webView loadRequest:request];
}
- (void)viewWillDisappear:(BOOL)animated;
{
// there is no point in continuing with the request load
// if somebody leaves this screen before its finished
[self.webView stopLoading];
}
@end
所以现在你需要在控制器中为前一个视图做的就是获取故事 URL,将它传递给 FirstViewController 并推送它。
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *story = [stories objectAtIndex:[indexPath row]];
NSURL *storyURL = [NSURL URLWithString:[story objectForKey:@"link"]];
FirstViewController *firstViewController = [[FirstViewController alloc] initWithNibName:@"FirstView" bundle:[NSBundle mainBundle]]; // I'm pretty sure you don't need to pass in the main bundle here
firstViewController.storyURL = storyURL;
[self.navigationController pushViewController:firstViewController animated:YES];
[firstViewController release]; // don't leak memory
}
就是这样。其他几点:
我假设您的字典中的“链接”值已经是一个字符串 - 如果是这种情况,则不需要在您的原始示例中构建一个全新的字符串。正如您在我的示例中所看到的,我们可以直接使用此字符串来创建NSURL
实例。
在您的原始代码中,当您分配/初始化您的 FirstViewController 时,您将其直接传递到pushViewController
. 这会造成内存泄漏,因为一旦UINavigationController
完成(在它从导航堆栈中弹出之后),它的保留计数仍然是 1。至少你应该调用autorelease
,但这里最有效的做法是简单地分配/初始化它,将它存储在一个临时变量中,然后release
在我们推送它之后直接调用。这确保了一旦它从导航堆栈中弹出,它将被释放。