原因:
程序中本來很多地方就是要用到配置檔.
比如: 蒼老師成功登錄了我的app(真希望是如此), 我這時候要保存她的用戶信息,等她下次打開app的時候,就能自動登錄了.
解決:
最簡單的方案,就是plist文件,實際上這就是個xml.
一開始在bundle中我們保持一個文件,然后把它copy到app的沙盒區(qū)域,然后再增加讀寫接口.
貌似真的很簡單.
- (void) createConfigFile
{
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"config" ofType:@"plist"];
NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
//獲取應(yīng)用程序沙盒的Documents目錄
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *filename=[[paths objectAtIndex:0] stringByAppendingPathComponent:@"config.plist"];
[data writeToFile:filename atomically:YES];
}
- (void) setKey:(NSString*)key Value:(NSString*)val
{
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *filename=[[paths objectAtIndex:0] stringByAppendingPathComponent:@"config.plist"];
NSMutableDictionary *data1 = [[NSMutableDictionary alloc] initWithContentsOfFile:filename];
[data1 setValue:val forKey:key];
[data1 writeToFile:filename atomically:YES];
}
- (NSString*) getKey:(NSString*)key
{
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *filename=[[paths objectAtIndex:0] stringByAppendingPathComponent:@"config.plist"];
NSMutableDictionary *data1 = [[NSMutableDictionary alloc] initWithContentsOfFile:filename];
return [data1 objectForKey:key];
}
要說的話:
注釋就不用了吧,润绎。
另外還有不盡如意的地方,比如每次寫操作都要同時寫文件,以前做C++的時候為了保證效率,總是先寫內(nèi)存中,然后再選擇一個合適的時機寫到文件中赞季,看起來是優(yōu)點效率損失烘豹,還有每次都要重新計算一下文件路徑青瀑,其實真的沒必要里逆,可以用一個成員變量保存起來刚照,這樣就不用重復(fù)計算了。
app的開發(fā)成本越來越低搂蜓,ios和Android cpu越來越強大,弄得我也沒心思像以前c++那樣優(yōu)化來辽装,優(yōu)化去帮碰,內(nèi)存池,線程池如迟,緩沖隊列,哎攻走,扯遠了殷勘。。