我正在寻找一些关于协议(protocol)和委托(delegate)在 Objective-C 中如何工作的额外解释/见解。我有一个正在开发的应用程序,它使用的是 UINavigationController。有一个主页和一个设置页面,这将允许用户输入一些将用作主页标题的文本。我已经实现并运行了所有内容,但我只需要澄清一下它是如何工作的。
这是一个如何设置的例子:
@interface MainPageViewController : UIViewController
@end
@interface MainPageViewController() <SettingsControllerDelegate>
// properties
@end
@implementation MainPageViewController
- (void)methodThatSetsTitle(NSString *)title
{
self.title = title;
}
@end
.....
@protocol SettingsControllerDelegate <NSObject>
{
- (void)methodThatSetsTitle(NSString *)title
}
@interface SettingsViewController
@property (weak, nonatomic) id <SettingsControllerDelegate> delegate;
@end
@interface SettingsViewController ()
// properties that will be used for a text field and holding an NSString
@end
@implementation SettingsViewController
- (void)methodThatPassesStringToDelegateProtocolMethod
{
// Code that will set the property for the NSString title
[self.delegate methodThatSetsTitle:self.titleNameProperty];
}
@end
我的问题是:SettingsViewController 中的 NSString 标题实际上是如何传递给 MainViewController 的?我的想法是,“委托(delegate)”属性被声明为 SettingsControllerDelegate,因此它本身可以保存来自协议(protocol)所具有的方法的信息。然后显然在 MainViewController 中我调用了相同的协议(protocol)方法,它将只接受参数并将当前导航标题设置为它。关于参数和方法信息存储在何处以供其他方法调用获取它只是有点令人困惑。每次我调用 SettingsViewController 方法时,'- (void)methodThatPassesStringToDelegateProtocolMethod' 是否只调用 MainViewController 中的方法?
(同样在我的代码中,我有一个 prepareForSegue 方法,它将 SettingViewController.delegate 设置为 self。)
如果能澄清此信息的传递方式及其工作原理的详细信息,那就太好了!我能理解其中的复杂性,但如果您能以一种全面且易于理解的方式对其进行解释,那就太好了。我可以理解内存模型等,因此解释它如何在内存中工作将非常有用。
非常感谢!
最佳答案
我认为您可能正在寻找的主要内容是 - delegate 属性到底是什么?声明
id<SettingsViewControllerDelegate> delegate;
表示您正在声明一个符合 SettingsViewControllerDelegate
协议(protocol)的对象 (id) - 这意味着它实现了 methodThatSetsTitle:
方法。这可以是任何对象,只要它符合该协议(protocol)即可。所以当你这样做时:
[self.delegate methodThatSetsTitle:self.titleNameProperty];
你正在向那个对象发送消息,不管它是什么,用给定的 NSString 做一些事情。
在您的特定情况下,您使用主页 View Controller 作为委托(delegate),因此上面的代码行从设置 View Controller 向主页 View Controller 发送一条消息,以将其标题设置为您发送的字符串作为论点。
就内存而言,将其视为任何其他“正常”实例方法。在这种情况下,委托(delegate)是主页面 View Controller ,因此它大概在导航堆栈上。
希望这对您有所帮助!
关于ios - 澄清 Objective-C 协议(protocol)和授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18320579/