標籤:
iOS中儲存的3中方式:
1.NSUserDefaults
注意儲存基本物件類型是沒有問題的,但是要儲存自訂對象,則要將對象內所有的屬性(或是需要儲存的屬性)序列化,實現NSCoding協議序列化。
存:
[[NSUserDefaults standardUserDefaults] setValue:@"yellow" forKey:@"color"];[[NSUserDefaults standardUserDefaults] synchronize];
取:
NSString *color = [[NSUserDefaults standardUserDefaults] objectForKey:@"color"];
對於儲存的是自訂的對象:(樣本Contact的序列化)
#import <Foundation/Foundation.h>@interface Contact : NSObject <NSCoding>@property (nonatomic,retain) NSString *name;@property (nonatomic,retain) NSString *phoneNumber;+ (id)contactsWithName:(NSString *)aName phoneNumber:(NSString *)aPhoneNumber;@end
#import "Contact.h"
#define kNameKey @"NameKey"#define kPhoneNumberKey @"PhoneNumberKey"@implementation Contact- (id)initWithName:(NSString *)aName phoneNumber:(NSString *)aPhoneNumber{ if (self = [super init]) { self.name = aName; self.phoneNumber = aPhoneNumber; } return self;}//初始化配套的便利方法 ,靜態方法中的self 不代表當前類的對象,代表當前類本身+ (id)contactsWithName:(NSString *)aName phoneNumber:(NSString *)aPhoneNumber{ return [[[self alloc] initWithName:aName phoneNumber:aPhoneNumber] autorelease]; }//對象序列化的兩個協議方法//對象序列化的方法,把對象的所有屬性編碼到本地- (void)encodeWithCoder:(NSCoder *)aCoder{ [aCoder encodeObject:_name forKey:kNameKey]; [aCoder encodeObject:_phoneNumber forKey:kPhoneNumberKey];}//對象還原序列化的方法- (id)initWithCoder:(NSCoder *)aDecoder{ if(self = [super init]) { self.name = [aDecoder decodeObjectForKey:kNameKey]; self.phoneNumber = [aDecoder decodeObjectForKey:kPhoneNumberKey]; } return self;}
2.沙箱
- (void)viewDidLoad { [super viewDidLoad]; NSMutableDictionary *savedDic = [[NSMutableDictionary alloc] initWithContentsOfFile:[self dataFilePath]]; //如果第一次進入,從userdefault中取不到資料,手動建立一個字典 if (!savedDic) { self.dic = [NSMutableDictionary dictionaryWithCapacity:0]; } else { self.dic = savedDic; } //註冊一個即將進入背景通知 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveData) name:UIApplicationWillResignActiveNotification object:nil]; }//返迴文件的路徑- (NSString *)dataFilePath{ //沙箱 //獲得沙箱下面Documents檔案夾的路徑 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSLog(@"paths %@",paths); NSString *path = [paths objectAtIndex:0]; //在documents 路徑下,追加一個檔案路徑 NSString *filePath = [path stringByAppendingPathComponent:@"select.plist"]; return filePath; }- (void)saveData{ //字典當中儲存的value 必須是 array dictionary Boolean data date nsnumber nsstring //把一個字典寫到檔案中,實際上是按照plist 的格式去組織資料的 [_dic writeToFile:[self dataFilePath] atomically:YES]; NSMutableDictionary *savedDic = [[NSMutableDictionary alloc] initWithContentsOfFile:[self dataFilePath]];}
3.sqlite
iOS儲存的三種方式