MST

星途 面试题库

面试题:Objective-C中代理模式的基本实现步骤

请简述在Objective-C中实现代理模式的基本步骤,并举例说明如何定义代理协议、设置代理以及在代理对象中响应方法。
40.5万 热度难度
编程语言Objective-C

知识考点

AI 面试

面试题答案

一键面试
  1. 定义代理协议

    • 代理协议定义了一系列方法,代理对象需要实现这些方法。使用@protocol关键字来定义协议。
    • 例如,假设有一个视图控制器ViewController,它可能需要一个代理来处理某些事件。定义如下协议:
    @protocol ViewControllerDelegate <NSObject>
    - (void)viewControllerDidFinish:(ViewController *)viewController;
    @end
    
    • 这里定义了一个ViewControllerDelegate协议,其中有一个viewControllerDidFinish:方法,当视图控制器完成某些操作时会调用这个方法。
  2. 设置代理

    • 在需要代理的类中,定义一个代理属性。通常使用weak修饰符(避免循环引用)。
    • 例如在ViewController类中:
    @interface ViewController : UIViewController
    @property (nonatomic, weak) id<ViewControllerDelegate> delegate;
    @end
    
    • 然后在某个地方设置代理,比如在另一个视图控制器中创建ViewController实例并设置代理:
    @interface AnotherViewController : UIViewController
    - (void)showViewController {
        ViewController *vc = [[ViewController alloc] init];
        vc.delegate = self;
        [self presentViewController:vc animated:YES completion:nil];
    }
    @end
    
    • 这里AnotherViewController创建了ViewController实例,并将自身设置为ViewController的代理。
  3. 在代理对象中响应方法

    • 代理对象需要遵守并实现代理协议中的方法。
    • 例如,在AnotherViewController类中实现ViewControllerDelegate协议的方法:
    @interface AnotherViewController () <ViewControllerDelegate>
    @end
    
    @implementation AnotherViewController
    - (void)viewControllerDidFinish:(ViewController *)viewController {
        NSLog(@"ViewController 完成操作,这里可以进行后续处理");
        [viewController dismissViewControllerAnimated:YES completion:nil];
    }
    @end
    
    • ViewController中调用[self.delegate viewControllerDidFinish:self];时,AnotherViewController中的viewControllerDidFinish:方法就会被调用,从而实现代理的功能。