先说一下几种常用的情况,NSUserDefaults 适合简单的页面传值。代理 主要用于一对一 可以传值,或在A页面对B页面进行操作,通知中心 主要用于一多对多 如换肤等。
从我个人觉得简单的开始:
1.NSUserDefaults: 使用 类似于字典(NSDictionary)
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];//单例模式创建 ud
[ud setObject:<#(id)#> forKey:<#(NSString *)#>];//存储OC对象(只能是OC对象)
[ud synchronize];//同步(类似数据库的同步)
********************************************************
[ud objectForKey:<#(NSString *)#>];//取数据 返回OC对象;
*****************************************************
[ud removeObjectForKey:<#(NSString *)#>];//删除
下面介绍几种存非OC对象常用的方法
- (void)setInteger:(NSInteger)value forKey:(NSString *)defaultName;
- (void)setFloat:(float)value forKey:(NSString *)defaultName;
- (void)setDouble:(double)value forKey:(NSString *)defaultName;
- (void)setBool:(BOOL)value forKey:(NSString *)defaultName;
- (void)setURL:(NSURL *)url forKey:(NSString *)defaultName NS_AVAILABLE(10_6, 4_0);(ios4.0以后可用)
2.代理:先讲代理是什么,个人理解 代理实质就是A页面通过B页面的指针 在A页面调用B页面的方法。让B页面进行一系列操作;(专业的东西都看起来很复杂。。。)(以在A页面要改变B页面颜色为例)
首先B页面要执行操作,所以B页面要实现方法去干活。。。跟现实中一样 干活的要签“合同”(这里遵循代理)
在.h里遵循代理
@interface MainViewController : UIViewController<SecondViewControllerDelegate>
{
}
.m里实现方法 并 传B页面的指针给A页面
-(void)changeColor{
self.view.backgroundColor = [UIColor redColor];
}
//传指针
svc = [[SecondViewControlleralloc]init];
svc.delegate = self;
B页面完成。
*****************************************************************************
A页面 要写合同(也就是写协议)
在.h里写协议
@protocol SecondViewControllerDelegate <NSObject>
-(void)changeColor;//声明要执行的B页面的方法
@end
声明协议的成员变量(实质就是用来接受B页面的指针用的,红色的是为了表明这个变量属于哪个代理,貌似是哈 我也不太清楚)
@interface SecondViewController : UIViewController
{
id<SecondViewControllerDelegate> delegate;
}
@property(nonatomic,weak)id <SecondViewControllerDelegate> delegate;
//weak 是为了防止循环引用(ARC)。非ARC(assign)
@end
——————————————————————————————————
.m文件
先synthesize一下 这就不多说了
@synthesize delegate = _delegate;
然后 在你想调方法的地方调方法就好了[_delegate changeColor];
代理就完成了。(传说中代理还是很强大的(协议里面可以写很多东西) 这只是最简单的应用)
————————————————————————————————————————————————————
————————————————————————————————————————————————————
通知中心:
发送通知:
[[NSNotificationCenterdefaultCenter]postNotificationName:@"MainNotification"object:svcuserInfo:@{@"123":@"hahahah"}];
黄色为通知的名字 可以随便;蓝色为给谁发通知 如果nil为所有注册过的人;绿色为字典NSDictionary 可以传一些需要的数据;
接受通知:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bbb:) name:@"MainNotification" object:nil];
接受名字为@“MainNotification”的通知,调用方法为bbb:
方法参数可以接受发送过来的字典
-(void)bbb:(NSNotification *)n
{
NSLog(@"%@",n.userInfo);
}
[[NSNotificationCenter defaultCenter] remove..... //删除
之后其他页面只要发送通知,接受通知的页面就会接到通知并执行相应的方法,
这个还是比较简单的。用完要删除 否则很占空间的
————————————————————————————————————————————————————————
KVO 目前还在学习中。以后会单独补一篇。