((精通iOS開發))第14章例子代碼小缺陷的修複

來源:互聯網
上載者:User

((精通iOS開發))第14章例子代碼小缺陷的修複

首先推薦大家看這本書,整本書邏輯非常清晰,代碼如何從無到有,到豐滿說的很有條理.

說實話本書到目前為止錯誤還是極少的,不過人無完人,在第14章前半部分項目的代碼中,作者在MasterVC到DetailVC中又直接添加了一個segue,該segue的ID為”masterToDetail”,作用是當建立一個tinyPix文檔時可以直接跳轉到DetailVC來編輯文檔.

作者同樣意識到如果直接從MasterVC的表視圖cell直接轉到DetailVC時也需要做一些額外的操作,該操作的作用是,當使用者點擊已存在的tinyPix時跳轉到DetailVC中開啟已存在的文檔.

作者是這樣修改prepareForSegue::方法的:

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{    if (sender == self) {        UIViewController *destination = segue.destinationViewController;        if ([destination respondsToSelector:@selector(setDetailItem:)]) {            [destination setValue:_chosenDoc forKey:@"detailItem"];        }    }else{        NSIndexPath *indexPath = self.tableView.indexPathForSelectedRow;        NSString *filename = _docFilenames[indexPath.row];        NSURL *docUrl = [self urlForFilename:filename];        _chosenDoc = [[HyTinyPixDocument alloc]initWithFileURL:docUrl];        [_chosenDoc openWithCompletionHandler:^(BOOL success){            if (success) {                UIViewController *destination = segue.destinationViewController;                if ([destination respondsToSelector:@selector(setDetailItem:)]) {                    [destination setValue:_chosenDoc forKey:@"detailItem"];                }            }else{                NSLog(@"failed to load!");            }        }];    }}

但是實際執行App時發現點擊已存在的tinyPix檔案並不能正確在DetailVC中顯示文檔的內容.在上述方法的else分支後下斷點,發現由TableViewCell跳轉而來的代碼其segue.destinationViewController並不是我們希望的DetailViewController,而是UINavigationController.而後者自然不存在神馬setDetailItem:方法.

我不知道這是作者的筆誤還是什麼其他原因,或者是新版的Xcode中Master-Detail Application模板發生了變化?但至少在Xcode7.2中情況是這樣.

那麼如何修複這個問題呢?其實比你想象的要簡單,修改如下:

if (success) {                //UIViewController *destination = segue.destinationViewController;                DetailViewController *detailVC = (DetailViewController*)[                                        segue.destinationViewController topViewController];                if ([detailVC respondsToSelector:@selector(setDetailItem:)]) {                    [detailVC setValue:_chosenDoc forKey:@"detailItem"];                }            }else{                NSLog(@"failed to load!");            }

在這裡我們需要的是destinationVC的topViewController對象,而不是destinationVC本身.

編譯串連App,現在兩種方法進入到DetailVC都表現正常了:

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.