1、界面之间切换,导致数据的传递和改变,如何保证始终是对一份数据进行曹操,即对一个对象身上的属性数据进行操作,存取,设置,这是就要用到单例了,总之,单例保证了工程只有一个实例对象!thankyou!
真是糟糕,忘记哪里参考的代码,后面有时间再贴出参考网址哦,尊重,支持原创者
//.h
#import <Foundation/Foundation.h>
@interface WeatherManager : NSObject
@property (nonatomic,strong)NSMutableArray *cityDidChooseds; //用于城市选择
//提供一个类方法,返回内部唯一的一个变量
+(id)sharedWeatherManager;
@end
//.m
#import "WeatherManager.h"
@implementation WeatherManager
//定义一份变量(整个程序运行过程中,只有一份)
static id _instace;
//单例模式:设计
//(1)永远只分配一块内存来创建对象
//(2)提供一个类方法,返回内部唯一的一个变量
//(3)最好保证init方法也只初始化一次
-(id)init
{
// __block id obj=nil;
static id obj=nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if ((obj=[superinit]) !=nil) {
//加载所需的音乐资源
//....
// self.muscis=[NSMutableDictionary dictionary];
// self.muscis[@"1.mp3"]=1mp3数据;
// self.muscis[@"2.mp3"]=2mp3数据;
_cityDidChooseds = [NSMutableArrayarray];
_currentCity = [[NSStringalloc]init];
}
});
self=obj;
return self;
}
//重写该方法,控制内存的分配,永远只分配一次存储空间
+(id)allocWithZone:(struct_NSZone *)zone
{
//里面的代码只会执行一次
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instace=[superallocWithZone:zone];
});
return_instace;
}
//类方法
+(id)sharedWeatherManager
{
//里面的代码永远都只执行一次
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instace=[[selfalloc]init];
});
return_instace;
}
+(id)copyWithZone:(struct_NSZone *)zone
{
return_instace;
}
@end
2、单例在外面的调用
WeatherManager *weatherManager = [WeatherManager sharedWeatherManager];
[weatherManager.cityDidChooseds addObject:choosedCityName];
3、单例的代码片段,可以直接贴到你的代码里哦,.h和.m文件的下载,下面是下载的链接地址
http://download.csdn.net/detail/muzeng/8031619