面试题答案
一键面试-
定义代理协议:
- 代理协议定义了一系列方法,代理对象需要实现这些方法。使用
@protocol
关键字来定义协议。 - 例如,假设有一个视图控制器
ViewController
,它可能需要一个代理来处理某些事件。定义如下协议:
@protocol ViewControllerDelegate <NSObject> - (void)viewControllerDidFinish:(ViewController *)viewController; @end
- 这里定义了一个
ViewControllerDelegate
协议,其中有一个viewControllerDidFinish:
方法,当视图控制器完成某些操作时会调用这个方法。
- 代理协议定义了一系列方法,代理对象需要实现这些方法。使用
-
设置代理:
- 在需要代理的类中,定义一个代理属性。通常使用
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
的代理。
- 在需要代理的类中,定义一个代理属性。通常使用
-
在代理对象中响应方法:
- 代理对象需要遵守并实现代理协议中的方法。
- 例如,在
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:
方法就会被调用,从而实现代理的功能。