正如其他人所說,一般的想法是有存儲需要加載的URL FirstViewController的屬性,然後將該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
實例。
在你原來的代碼中,當你分配/ init你的FirstViewController時,你直接把它傳遞給pushViewController
。這會造成內存泄漏,因爲一旦UINavigationController
完成(在它從導航堆棧彈出之後),它的保留計數仍然是1.至少應該調用autorelease
,但這裏要做的最有效的事情就是alloc /初始化它,將它存儲在一個臨時變量中,然後在我們推送它之後立即調用release
。這確保了一旦它從導航堆棧彈出,它就會被釋放。
真棒解釋 - 非常感謝! – 2009-07-24 20:06:00
我會在'viewDidLoad'而不是'viewDidAppear'中執行'loadRequest',否則,你會繼續重新加載頁面。你有一個可以切換視圖的標籤控制器。 – 2009-07-24 21:41:36
對於學習,我可以請求一個可下載的示例應用程序在XCode中查看以上內容嗎? – testndtv 2011-10-30 09:47:48