2016-02-01 31 views
0

该应用程序旨在让用户敲击表A中的单元格,然后转到表B以添加自定义类别,最后将此类别名称发送回表A并更改类别标签。协议在两个UITbaleViewControllers之间不起作用

class AddNote: UITableViewController, CatDelegate { 

    func selectCategory(theCatgory:String){ 
     customCategory.text = theCatgory 
    } 
    override func viewDidLoad() { 
     // .... 
    } 
} 

表B:

protocol CatDelegate:NSObjectProtocol{ 
    func selectCategory(theCatgory:String) 
} 

class SetCategory:UITableViewController{ 

    var theDelegate:CatDelegate? 

    override func viewDidLoad() { 
     // test to print out the string 
     self.theDelegate?.selectCategory("My Category") 
    } 
    // ...... 

} 

谁能帮助

这似乎不符合下列代码

表工作?谢谢。

+2

你设置'theDelegate'至表A? –

+0

为自己分配“TheDelegate”。 –

回答

-1

请参考这一个,可能会帮助你协议问题。 https://github.com/Vickita/ProtocolDemo

+0

是的。我得到它的工作参考你的示例代码。谢谢。 – jdleung

+0

虽然这可能在理论上回答这个问题,但[这将是更可取的](// meta.stackoverflow.com/q/8259)在这里包含答案的基本部分,并提供供参考的链接。 – SmokeDispenser

1

从我的代码中可以看到,当您展示第二个视图控制器时,实际上并没有设置委托。

线

self.theDelegate?.selectCategory("My Category") 

不会叫selectCategory()也没有提高,因为一个异常(好习惯!)?运营商如果self.theDelegatenil。它只会默默无闻。

作为一个快速检查,你可以用!代替?进行开发 - 当它遇到nil时会引发运行时异常。

+0

你是对的,当我使用'!'时,应用程序崩溃为零。实际上,这个协议在UIViewController和UIView之间使用。我只是不知道为什么它不能在两个UITableViewControllers之间工作。 – jdleung

+0

因为在这种情况下'viewDidLoad'被调用才能设置委托。 – SmokeDispenser

+0

我试图把它放在'tableView didSelectRowAtIndexPath'中,它也返回零 – jdleung

0

表A

In AddNote class 
    protocol CatDelegate /////above class declaration 
    { 
     func selectCategory(theCatgory:String) 

    } 
    class AddNote: NSObject 
    { 
      var theDelegate : CatDelegate? 


     } 

在任何功能,以火委托函数

     if (self.delegate != nil) 
        { 
         self.delegate?. selectCategory("My Category") 
        } 

表B

 override func viewDidLoad() 
      { 
     var addNote : AddNote! 
     addNote = AddNote() 
     addNote.theDelegate = self 
      } 
func selectCategory(theCatgory:String) 
    { 
///////// any thing view related 
    } 
+0

对不起,它不起作用,而且看起来相反。我需要更改表A的标签。 – jdleung

相关问题