iOS设计模式–总结
iOS Design Patterns中介绍常用设计模式如下:
以个人经历而言,主要接触到单例模式,MVC模式,MVVM模式,观察者模式 等等。
MVC模式
MVC模式包含Model,View,和Controller,是iOS最基本的设计模式,无需过多介绍。
单例模式
常见单例模式应用:
- [NSUserDefaults standardUserDefaults]
- [UIApplication sharedApplication]
- [UIScreen mainScreen]
- [NSFileManager defaultManager]
例如判断引导页实现时需要利用[NSUserDefaults standardUserDefaults]存储当前版本信息并进行判断决定是否显示引导页。
AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
通过[UIApplication sharedApplication]获取AppDelegate协议;
观察者模式
Notifications
Key-Value Observing (KVO)
Notifications
[[NSNotificationCenter defaultCenter] postNotificationName:textFieldDidBeginEditing object:self];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidBeginEditing) name:textFieldDidBeginEditing object:nil];
-(void) textFieldDidBeginEditing:(UITextField *)textField {
[UIView animateWithDuration:0.2 delay:0.0 usingSpringWithDamping:1.0 initialSpringVelocity:0.5 options:UIViewAnimationOptionTransitionCurlDown animations: ^{
self.userView.transform = CGAffineTransformMakeTranslation(0, -50);
} completion:nil];
}
通过监听键盘输入状态判断是否执行动画操作;
Key-Value Observing (KVO)
[coverImage addObserver:self forKeyPath:@”image” options:0 context:nil];
-(void)dealloc
{
[coverImage removeObserver:self forKeyPath:@”image”];
}
-(void)observeValueForKeyPath:(NSString )keyPath ofObject:(id)object change:(NSDictionary )change context:(void *)context
{
if ([keyPath isEqualToString:@”image”])
{
[indicator stopAnimating];
}
}
通过监听image属性判断是都执行动画;
备忘录模式
[NSUserDefaults standardUserDefaults defaults setBool:YES forKey:@”isLogin”];
通过NSUserDefaults记录应用登录状态;
if ([[NSUserDefaults standardUserDefaults] boolForKey:@”isLogin”]) {
return;
}
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@”More” bundle:nil];
SignViewController *controller = [storyboard instantiateViewControllerWithIdentifier:@”Sign”];
[self presentViewController:controller animated:YES completion:nil];
通过读取NSUserDefaults读取登录状态;
装饰器模式
Category
Delegate
分类和协议是Objective-c基本概念,此处略过;
命令模式
The Command design pattern encapsulates a request or action as an object. The encapsulated request is much more flexible than a raw request and can be passed between objects, stored for later, modified dynamically, or placed into a queue. Apple has implemented this pattern using the Target-Action mechanism and Invocation.
目前主要接触到 Target-Action 。
UIBarButtonItem *button = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(takePhoto)];
为button添加方法:takePhoto,当点击此button时,执行takePhoto方法。

被折叠的 条评论
为什么被折叠?



