iOS开发中的几种模式总结

1.代理模式

在开发中我们经常使用代理,或自己写个代理,而代理属性都用weak(assign)修饰,看过有些开发者用strong(retain),但并没发现有何不妥,也不清楚weak(assign)与strong(retain)修饰有何区别

功能实现就行了,考虑这么多干嘛~~~我只能哈哈哈

weak:指明该对象并不负责保持delegate这个对象,delegate这个对象的销毁由外部控制

@property (nonatomic, weak) iddelegate;

strong:该对象强引用delegate,外界不能销毁delegate对象,会导致循环引用(Retain Cycles)

@property (nonatomic, strong) iddelegate;

谁提出代理就在该类写一个代理协议和声明一个代理人(一定要weak修饰代理人)

//其他类实现这个代理的话就要签订协议

2.KVO观察者模式

//赋值的时候必须用self取值不能用下划线取值

//b) 给模态视图定义一个观察者

[_modalViewController addObserver:self

forKeyPath:@"textLabel"

options:NSKeyValueObservingOptionNew

context:nil];

//方法

- (void) observeValueForKeyPath:(NSString *)keyPath

ofObject:(id)object

change:(NSDictionary *)change

context:(void *)context {

// NSLog(@"old = %@, new = %@", [change objectForKey:@"old"], [change objectForKey:@"new"]);

//1) 获取值得变化

NSString *text = [change objectForKey:@"new"];

//2) 通过tage获取label

UILabel *label = (UILabel *) [self.view viewWithTag:1000];

//3) 改变label的值

label.text = text;

}

3.通知

// 发送通知

NSDictionary *userInfo = @{@"text" : textField.text};

[[NSNotificationCenter defaultCenter] postNotificationName:kTextFieldTextChangeNotification

object:nil

userInfo:userInfo];

//接收通知

[[NSNotificationCenter defaultCenter] addObserver:self

selector:@selector(receiveNotification:)

name:kTextFieldTextChangeNotification

object:nil];

4.单例方法

//1. 定义一个静态全局变量

static RootViewController *instance = nil;

@implementation RootViewController

//2. 实现类方法

+ (instancetype) sharedInstance {

@synchronized(self) {

if (instance == nil) {

//初始化单例模式

instance = [[RootViewController alloc] init];

}

}

return instance;

}

//说明:这里的的复写目的是防止用户无意之间采用[[RootViewController alloc] init]进行初始化

+ (instancetype) allocWithZone:(struct _NSZone *)zone {

@synchronized(self) {

if (instance == nil) {

//说明:这里的实例是进行内存的分配

instance = [super allocWithZone: zone];

}

}

return instance;

}

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容