objective-C 沙盒存儲

沙盒存儲——plist


1111.png

屬性列表是一種XML格式的文件志秃,拓展名為plist房待。如果對象是NSString邢羔、NSDictionary驼抹、NSArray、NSData拜鹤、NSNumber等類型框冀,就可以使用writeToFile:atomically:方法直接將對象寫到屬性列表文件中

如果是其他類型的的對象,需要使用plist儲存敏簿,需要轉(zhuǎn)類型:
例如://轉(zhuǎn)化Data
NSData * imageData = UIImagePNGRepresentation(getImage);

存:

//獲取路徑
// NSSearchPath尋找路徑
// ForDirectories要找的文件夾
// InDomains在哪個地方找
// NSDocumentDirectory Documents

NSString *docPath=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)[0];      
//拼接路徑   
NSString *filePath = [docPath stringByAppendingPathComponent:@"xxxx.plist"];
 
//創(chuàng)建字典
NSDictionary *dict =@{@"name":@"laoma",@"age":@"18"};

// 存儲字典
[dict writeToFile:filePath atomically:YES];

让饕病:

   //獲取doc路徑   
NSString *docPath =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)[0];      
//拼接plist路徑   
NSString *filePath = [docPath stringByAppendingPathComponent:@"xxxx.plist"];      
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:filePath];   

NSLog(@"%@",dict[@"name"]);

字符串存取

- (IBAction)save:(id)sender {
   //獲取docpath
   NSString *docpath =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)[0];

   //拼接路徑
   NSString *filepath = [docpath stringByAppendingPathComponent:@"x.plist"];

   NSString *str =@“hello word"
;
   [str writeToFile:filepath atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
- (IBAction)read:(id)sender {

   //獲取docpath   
NSString *docpath =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)[0];     
//拼接路徑   
NSString *filepath = [docpath stringByAppendingPathComponent:@"x.plist"];   
   // 獲取字符串
NSString *str = [NSString stringWithContentsOfFile:filepath encoding:NSUTF8StringEncoding error:nil];
NSLog(@"%@",str);
}


沙盒儲存——?dú)w檔解檔

#import<Foundation/Foundation.h>
@interface Person :NSObject<NSCoding>
@property(nonatomic,copy)NSString *name;

@property(nonatomic,assign)NSInteger age;
@end
#import"Person.h"
@implementationPerson

//告訴系統(tǒng)歸檔哪些屬性
- (void)encodeWithCoder:(NSCoder *)aCoder {      
  [aCoder encodeObject:_name forKey:@"name"]; 
  [aCoder encodeInteger:_age forKey:@"age"];
}
//告訴系統(tǒng)解檔哪些屬性,如何解檔
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
  if(self= [super init]) { 
    _name= [aDecoder decodeObjectForKey:@"name"]; 
    _age= [aDecoder decodeIntegerForKey:@"age"];    
  }   
  return self;
}
@end
#import "ViewController.h"
#import "Person.h"
@interface ViewController()
@end
@implementation ViewController
//歸檔
- (IBAction)save:(id)sender {      
//創(chuàng)建對象   
Personn*p = [[Person alloc]init];       
p.name=@"zhangsan";    
p.age=18;      
// docpath   
NSString *docPath =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)[0];      
// 拼接路徑   
NSString *fliePath = [docPath stringByAppendingPathComponent:@"person.data"];      
//歸檔    
[NSKeyedArchiver archiveRootObject:p toFile:fliePath];   
}


//解檔
- (IBAction)read:(id)sender {      
// docpath   
NSString *docPath =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)[0];      
// 拼接路徑   
NSString *fliePath = [docPath stringByAppendingPathComponent:@"person.data"];      
//解檔   
Person *p = [NSKeyedUnarchiver unarchiveObjectWithFile:fliePath];      
NSLog(@"%@",p.name);
}

- (void)viewDidLoad {    
[super viewDidLoad];   
// Do any additional setup after loading the view, typically from a nib.}
- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];   
// Dispose of any resources that can be recreated.}
@end


沙盒存儲——偏好設(shè)置userDefaults

保存設(shè)置

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

[defaults setObject:@"itcast"  forKey:@"username"];

[defaults setFloat:18.0f  forKey:@"text_size"];

[defaults setBool:YES  forKey:@"auto_login"];

讀取上次保存的設(shè)置

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *username = [defaults stringForKey:@"username"];
float textSize = [defaults floatForKey:@"text_size"];
BOOL autoLogin = [defaults boolForKey:@"auto_login"];

注意:UserDefaults設(shè)置數(shù)據(jù)時,不是立即寫入惯裕,而是根據(jù)時間戳定時地把緩存中的數(shù)據(jù)寫入本地磁盤温数。所以調(diào)用了set方法之后數(shù)據(jù)有可能還沒有寫入磁盤應(yīng)用程序就終止了。出現(xiàn)以上問題蜻势,可以通過調(diào)用synchornize方法強(qiáng)制寫入

[defaults synchornize];
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末撑刺,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子握玛,更是在濱河造成了極大的恐慌够傍,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,277評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件挠铲,死亡現(xiàn)場離奇詭異冕屯,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)拂苹,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評論 3 393
  • 文/潘曉璐 我一進(jìn)店門安聘,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人醋寝,你說我怎么就攤上這事搞挣。” “怎么了音羞?”我有些...
    開封第一講書人閱讀 163,624評論 0 353
  • 文/不壞的土叔 我叫張陵囱桨,是天一觀的道長。 經(jīng)常有香客問我嗅绰,道長舍肠,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,356評論 1 293
  • 正文 為了忘掉前任窘面,我火速辦了婚禮翠语,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘财边。我一直安慰自己肌括,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,402評論 6 392
  • 文/花漫 我一把揭開白布酣难。 她就那樣靜靜地躺著谍夭,像睡著了一般黑滴。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上紧索,一...
    開封第一講書人閱讀 51,292評論 1 301
  • 那天袁辈,我揣著相機(jī)與錄音,去河邊找鬼珠漂。 笑死晚缩,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的媳危。 我是一名探鬼主播荞彼,決...
    沈念sama閱讀 40,135評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼济舆!你這毒婦竟也來了卿泽?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,992評論 0 275
  • 序言:老撾萬榮一對情侶失蹤滋觉,失蹤者是張志新(化名)和其女友劉穎签夭,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體椎侠,經(jīng)...
    沈念sama閱讀 45,429評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡第租,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,636評論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了我纪。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片慎宾。...
    茶點(diǎn)故事閱讀 39,785評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖浅悉,靈堂內(nèi)的尸體忽然破棺而出趟据,到底是詐尸還是另有隱情,我是刑警寧澤术健,帶...
    沈念sama閱讀 35,492評論 5 345
  • 正文 年R本政府宣布汹碱,位于F島的核電站,受9級特大地震影響荞估,放射性物質(zhì)發(fā)生泄漏咳促。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,092評論 3 328
  • 文/蒙蒙 一勘伺、第九天 我趴在偏房一處隱蔽的房頂上張望跪腹。 院中可真熱鬧,春花似錦飞醉、人聲如沸冲茸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽噪裕。三九已至蹲盘,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間膳音,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評論 1 269
  • 我被黑心中介騙來泰國打工铃诬, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留祭陷,地道東北人。 一個月前我還...
    沈念sama閱讀 47,891評論 2 370
  • 正文 我出身青樓趣席,卻偏偏與公主長得像兵志,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子宣肚,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,713評論 2 354

推薦閱讀更多精彩內(nèi)容