起点
我有一个类,比如说 A ,由UI视图使用
A 有一个委托应该通知UI视图,这个应该在屏幕上写一些东西。
问题
实现此功能的最佳方法是什么?
看起来像观察者可观察的模式
代码
--- A.H
@interface A : NSObject
@end
--- A.M
@implementation A
-(void)fooDelegate:(FooType *)sender {
/* Here I need to notify UI (that change notificationArea.text) */
}
--- UIView.h
@interface UIView : UIViewController
@property(strong, nonatomic, retain) A* a;
@property(strong, nonatomic) IBOutlet UITextField *notificationArea;
@end
答案 0 :(得分:1)
根据评论,我想只是代码是您正在寻找的......
创建您的委托协议:
@protocol ADelegate;
@interface A : NSObject
@property (nonatomic, weak) id <ADelegate> delegate;
@end
@protocol ADelegate <NSObject>
@optional
-(void)fooDelegate:(A *)a;
@end
通知您的代表:
@implementation A
-(void)fooDelegate:(FooType *)sender {
if ([[self delegate] respondsToSelector:@selector(fooDelegate:)]) {
[[self delegate] fooDelegate:self];
}
}
@end
遵守代表协议:
#import "A.h"
#import "MyView.h"
@interface MyView <ADelegate>
@end
@implementation MyView
-(void)fooDelegate:(A *)a {
// update text field here
}
@end
最后,每当您创建A
的实例时,请设置委托(此示例中的self
是MyView
的实例:
A *a = [[A alloc] init];
[a setDelegate:self];