NSUserDefaults
, NSCoding
, SQLite
, CoreData
.....),傳聞最簡單的是 NSUserDefaults
。由於
NSUserDefaults
只接受 NSData
, NSString
, NSNumber
, NSArray
, NSDictionary
。NSMutableArray的好處, 是可以隨時增刪內容, 長度是不用固定的
。因此要存
NSMutableArray
的話,得轉回 NSArray
。 - (void) loadData
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *string = [prefs stringForKey:@"stringKey"]; //讀取
NSArray *array = [prefs arrayForKey:@"arrayKey"];
if (array == NULL)
{ array = [NSArray arrayWithObjects:@"strin1", @"string2", nil]; [prefs setObject:array forKey:@"
arrayKey
"]; }
}
- (void) saveData
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:@"string1" forKey:@"
stringKey
"];
NSArray *array = [prefs arrayForKey:@"
arrayKey
"];
//讀取
NSMutableArray *Marray = [array mutableCopy]; //NSArray 轉 NSMutableArray //[Marray addObject: @"coconut"]; array = [NSArray arrayWithArray:Marray]; //NSMutableArray 轉 NSArray [prefs setObject:array forKey:@"
arrayKey
"];
[prefs synchronize]; //
確保資料被寫入}
沒有留言:
張貼留言