Bên cạnh phương pháp tiếp cận NSUserDefaults rất tốt, có một cách dễ dàng khác để lưu trữ dữ liệu từ NSArray, NSDictionary hoặc NSData trong một tệp. Bạn có thể sử dụng những phương pháp cũng như:
- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag
tương ứng (đối với một NSDictionary):
+ (id)dictionaryWithContentsOfFile:(NSString *)path
bạn chỉ cần đưa ra một đường dẫn hợp lệ đến một địa điểm. Theo Hướng dẫn lập trình ứng dụng iOS, thư mục/Library/Caches sẽ là nơi tốt nhất để lưu trữ dữ liệu mà bạn cần phải tồn tại giữa các lần khởi chạy ứng dụng. (Xem here)
Để lưu trữ/nạp một cuốn từ điển từ một đệ được gọi là "nhà quản lý" trong tài liệu của bạn directoy bạn có thể sử dụng các phương pháp:
-(void) loadDictionary {
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSCachesDirectory, NSUserDomainMask, YES);
NSString *cacheDirectory = [paths objectAtIndex:0];
//create a destination file name to write the data :
NSString *fullFileName = [NSString stringWithFormat:@"%@/managers", cacheDirectory];
NSDictionary* panelLibraryContent = [NSDictionary dictionaryWithContentsOfFile:fullFileName];
if (panelLibraryContent != nil) {
// load was successful do something with the data...
} else {
// error while loading the file
}
}
-(void) storeDictionary:(NSDictionary*) dictionaryToStore {
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cacheDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the
//cache directory:
NSString *fullFileName = [NSString stringWithFormat:@"%@/managers", cacheDirectory];
if (dictionaryToStore != nil) {
[dictionaryToStore writeToFile:fullFileName atomically:YES];
}
}
Dù sao phương pháp này là rất hạn chế và bạn phải dành nhiều công sức hơn nếu bạn muốn lưu trữ dữ liệu phức tạp hơn. Trong trường hợp đó, API CoreData rất tiện dụng.
Perfect! Cảm ơn! – Toastor
'-setValue: forKey:' và '-valueForKey', tương ứng, cũng tốt. Hơn nữa, 'standardUserDefaults' luôn được sao lưu khi một iDevice được đồng bộ. Điều này thật tuyệt nếu bạn muốn bao gồm mua hàng trong ứng dụng. – SK9
Cảm ơn làm việc hoàn hảo rất tốt –