IOS 数据存储

ios数据存储包括以下几种存储机制:

属性列表

对象归档

SQLite3

CoreData

AppSettings

普通文件存储

1、属性列表

  1. //
  2. //  Persistence1ViewController.h
  3. //  Persistence1
  4. //
  5. //  Created by liu lavy on 11-10-3.
  6. //  Copyright 2011 __MyCompanyName__. All rights reserved.
  7. //
  8. #import <UIKit/UIKit.h>
  9. #define kFilename @"data.plist"
  10. @interface Persistence1ViewController : UIViewController {
  11. UITextField *filed1;
  12. UITextField *field2;
  13. UITextField *field3;
  14. UITextField *field4;
  15. }
  16. @property (nonatomic, retain) IBOutlet UITextField *field1;
  17. @property (nonatomic, retain) IBOutlet UITextField *field2;
  18. @property (nonatomic, retain) IBOutlet UITextField *field3;
  19. @property (nonatomic, retain) IBOutlet UITextField *field4;
  20. - (NSString *)dataFilePath;
  21. - (void)applicationWillResignActive:(NSNotification *)notification;
  22. @end
  1. //
  2. //  Persistence1ViewController.m
  3. //  Persistence1
  4. //
  5. //  Created by liu lavy on 11-10-3.
  6. //  Copyright 2011 __MyCompanyName__. All rights reserved.
  7. //
  8. #import "Persistence1ViewController.h"
  9. @implementation Persistence1ViewController
  10. @synthesize field1;
  11. @synthesize field2;
  12. @synthesize field3;
  13. @synthesize field4;
  14. //数据文件的完整路径
  15. - (NSString *)dataFilePath {
  16. //检索Documents目录路径。第二个参数表示将搜索限制在我们的应用程序沙盒中
  17. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  18. //每个应用程序只有一个Documents目录
  19. NSString *documentsDirectory = [paths objectAtIndex:0];
  20. //创建文件名
  21. return [documentsDirectory stringByAppendingPathComponent:kFilename];
  22. }
  23. //应用程序退出时,将数据保存到属性列表文件
  24. - (void)applicationWillResignActive:(NSNotification *)notification {
  25. NSMutableArray *array = [[NSMutableArray alloc] init];
  26. [array addObject: field1.text];
  27. [array addObject: field2.text];
  28. [array addObject: field3.text];
  29. [array addObject: field4.text];
  30. [array writeToFile:[self dataFilePath] atomically:YES];
  31. [array release];
  32. }
  33. /*
  34. // The designated initializer. Override to perform setup that is required before the view is loaded.
  35. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
  36. self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
  37. if (self) {
  38. // Custom initialization
  39. }
  40. return self;
  41. }
  42. */
  43. /*
  44. // Implement loadView to create a view hierarchy programmatically, without using a nib.
  45. - (void)loadView {
  46. }
  47. */
  48. // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
  49. - (void)viewDidLoad {
  50. [super viewDidLoad];
  51. NSString *filePath = [self dataFilePath];
  52. //检查数据文件是否存在
  53. if([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
  54. NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
  55. field1.text = [array objectAtIndex:0];
  56. field2.text = [array objectAtIndex:1];
  57. field3.text = [array objectAtIndex:2];
  58. field4.text = [array objectAtIndex:3];
  59. [array release];
  60. }
  61. UIApplication *app = [UIApplication sharedApplication];
  62. [[NSNotificationCenter defaultCenter] addObserver:self
  63. selector:@selector(applicationWillResignActive:)
  64. name:UIApplicationWillResignActiveNotification
  65. object:app];
  66. [super viewDidLoad];
  67. }
  68. /*
  69. // Override to allow orientations other than the default portrait orientation.
  70. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
  71. // Return YES for supported orientations
  72. return (interfaceOrientation == UIInterfaceOrientationPortrait);
  73. }
  74. */
  75. - (void)didReceiveMemoryWarning {
  76. // Releases the view if it doesn't have a superview.
  77. [super didReceiveMemoryWarning];
  78. // Release any cached data, images, etc that aren't in use.
  79. }
  80. - (void)viewDidUnload {
  81. self.field1 = nil;
  82. self.field2 = nil;
  83. self.field3 = nil;
  84. self.field4 = nil;
  85. [super viewDidUnload];
  86. }
  87. - (void)dealloc {
  88. [field1 release];
  89. [field2 release];
  90. [field3 release];
  91. [field4 release];
  92. [super dealloc];
  93. }
  94. @end

===================================================================================

===================================================================================

2、对象归档

  1. //
  2. //  Fourlines.h
  3. //  Persistence2
  4. //
  5. //  Created by liu lavy on 11-10-3.
  6. //  Copyright 2011 __MyCompanyName__. All rights reserved.
  7. //
  8. #import <Foundation/Foundation.h>
  9. @interface Fourlines : NSObject <NSCoding, NSCopying> {
  10. NSString *field1;
  11. NSString *field2;
  12. NSString *field3;
  13. NSString *field4;
  14. }
  15. @property (nonatomic, retain) NSString *field1;
  16. @property (nonatomic, retain) NSString *field2;
  17. @property (nonatomic, retain) NSString *field3;
  18. @property (nonatomic, retain) NSString *field4;
  19. @end
  1. //
  2. //  Fourlines.m
  3. //  Persistence2
  4. //
  5. //  Created by liu lavy on 11-10-3.
  6. //  Copyright 2011 __MyCompanyName__. All rights reserved.
  7. //
  8. #import "Fourlines.h"
  9. #define kField1Key @"Field1"
  10. #define kField2Key @"Field2"
  11. #define kField3Key @"Field3"
  12. #define kField4Key @"Field4"
  13. @implementation Fourlines
  14. @synthesize field1;
  15. @synthesize field2;
  16. @synthesize field3;
  17. @synthesize field4;
  18. #pragma mark NSCoding
  19. - (void)encodeWithCoder:(NSCoder *)aCoder {
  20. [aCoder encodeObject:field1 forKey:kField1Key];
  21. [aCoder encodeObject:field2 forKey:kField2Key];
  22. [aCoder encodeObject:field3 forKey:kField3Key];
  23. [aCoder encodeObject:field4 forKey:kField4Key];
  24. }
  25. -(id) initWithCoder:(NSCoder *)aDecoder {
  26. if(self = [super init]) {
  27. field1 = [[aDecoder decodeObjectForKey:kField1Key] retain];
  28. field2 = [[aDecoder decodeObjectForKey:kField2Key] retain];
  29. field3 = [[aDecoder decodeObjectForKey:kField3Key] retain];
  30. field4 = [[aDecoder decodeObjectForKey:kField4Key] retain];
  31. }
  32. return self;
  33. }
  34. #pragma mark -
  35. #pragma mark NSCopying
  36. - (id) copyWithZone:(NSZone *)zone {
  37. Fourlines *copy = [[[self class] allocWithZone: zone] init];
  38. copy.field1 = [[self.field1 copyWithZone: zone] autorelease];
  39. copy.field2 = [[self.field2 copyWithZone: zone] autorelease];
  40. copy.field3 = [[self.field3 copyWithZone: zone] autorelease];
  41. copy.field4 = [[self.field4 copyWithZone: zone] autorelease];
  42. return copy;
  43. }
  44. @end
  1. //
  2. //  Persistence2ViewController.h
  3. //  Persistence2
  4. //
  5. //  Created by liu lavy on 11-10-3.
  6. //  Copyright 2011 __MyCompanyName__. All rights reserved.
  7. //
  8. #import <UIKit/UIKit.h>
  9. #define kFilename @"archive"
  10. #define kDataKey @"Data"
  11. @interface Persistence2ViewController : UIViewController {
  12. UITextField *filed1;
  13. UITextField *field2;
  14. UITextField *field3;
  15. UITextField *field4;
  16. }
  17. @property (nonatomic, retain) IBOutlet UITextField *field1;
  18. @property (nonatomic, retain) IBOutlet UITextField *field2;
  19. @property (nonatomic, retain) IBOutlet UITextField *field3;
  20. @property (nonatomic, retain) IBOutlet UITextField *field4;
  21. - (NSString *)dataFilePath;
  22. - (void)applicationWillResignActive:(NSNotification *)notification;
  23. @end
  1. //
  2. //  Persistence2ViewController.m
  3. //  Persistence2
  4. //
  5. //  Created by liu lavy on 11-10-3.
  6. //  Copyright 2011 __MyCompanyName__. All rights reserved.
  7. //
  8. #import "Persistence2ViewController.h"
  9. #import "Fourlines.h"
  10. @implementation Persistence2ViewController
  11. @synthesize field1;
  12. @synthesize field2;
  13. @synthesize field3;
  14. @synthesize field4;
  15. //数据文件的完整路径
  16. - (NSString *)dataFilePath {
  17. //检索Documents目录路径。第二个参数表示将搜索限制在我们的应用程序沙盒中
  18. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  19. //每个应用程序只有一个Documents目录
  20. NSString *documentsDirectory = [paths objectAtIndex:0];
  21. //创建文件名
  22. return [documentsDirectory stringByAppendingPathComponent:kFilename];
  23. }
  24. //应用程序退出时,将数据保存到属性列表文件
  25. - (void)applicationWillResignActive:(NSNotification *)notification {
  26. Fourlines *fourlines = [[Fourlines alloc] init];
  27. fourlines.field1 = field1.text;
  28. fourlines.field2 = field2.text;
  29. fourlines.field3 = field3.text;
  30. fourlines.field4 = field4.text;
  31. NSMutableData *data = [[NSMutableData alloc] init];//用于存储编码的数据
  32. NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
  33. [archiver encodeObject:fourlines forKey:kDataKey];
  34. [archiver finishEncoding];
  35. [data writeToFile:[self dataFilePath] atomically:YES];
  36. [fourlines release];
  37. [archiver release];
  38. [data release];
  39. }
  40. /*
  41. // The designated initializer. Override to perform setup that is required before the view is loaded.
  42. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
  43. self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
  44. if (self) {
  45. // Custom initialization
  46. }
  47. return self;
  48. }
  49. */
  50. /*
  51. // Implement loadView to create a view hierarchy programmatically, without using a nib.
  52. - (void)loadView {
  53. }
  54. */
  55. // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
  56. - (void)viewDidLoad {
  57. [super viewDidLoad];
  58. NSString *filePath = [self dataFilePath];
  59. //检查数据文件是否存在
  60. if([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
  61. //从文件获取用于解码的数据
  62. NSData *data = [[NSMutableData alloc] initWithContentsOfFile:[self dataFilePath]];
  63. NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
  64. Fourlines *fourlines = [unarchiver decodeObjectForKey:kDataKey];
  65. [unarchiver finishDecoding];
  66. field1.text = fourlines.field1;
  67. field2.text = fourlines.field2;
  68. field3.text = fourlines.field3;
  69. field4.text = fourlines.field4;
  70. [unarchiver release];
  71. [data release];
  72. }
  73. UIApplication *app = [UIApplication sharedApplication];
  74. [[NSNotificationCenter defaultCenter] addObserver:self
  75. selector:@selector(applicationWillResignActive:)
  76. name:UIApplicationWillResignActiveNotification
  77. object:app];
  78. [super viewDidLoad];
  79. }
  80. /*
  81. // Override to allow orientations other than the default portrait orientation.
  82. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
  83. // Return YES for supported orientations
  84. return (interfaceOrientation == UIInterfaceOrientationPortrait);
  85. }
  86. */
  87. - (void)didReceiveMemoryWarning {
  88. // Releases the view if it doesn't have a superview.
  89. [super didReceiveMemoryWarning];
  90. // Release any cached data, images, etc that aren't in use.
  91. }
  92. - (void)viewDidUnload {
  93. self.field1 = nil;
  94. self.field2 = nil;
  95. self.field3 = nil;
  96. self.field4 = nil;
  97. [super viewDidUnload];
  98. }
  99. - (void)dealloc {
  100. [field1 release];
  101. [field2 release];
  102. [field3 release];
  103. [field4 release];
  104. [super dealloc];
  105. }
  106. @end

===================================================================================

===================================================================================

3、SQLite

  1. //
  2. //  Persistence3ViewController.h
  3. //  Persistence3
  4. //
  5. //  Created by liu lavy on 11-10-3.
  6. //  Copyright 2011 __MyCompanyName__. All rights reserved.
  7. //
  8. #import <UIKit/UIKit.h>
  9. #define kFilename @"data.sqlite3"
  10. @interface Persistence3ViewController : UIViewController {
  11. UITextField *filed1;
  12. UITextField *field2;
  13. UITextField *field3;
  14. UITextField *field4;
  15. }
  16. @property (nonatomic, retain) IBOutlet UITextField *field1;
  17. @property (nonatomic, retain) IBOutlet UITextField *field2;
  18. @property (nonatomic, retain) IBOutlet UITextField *field3;
  19. @property (nonatomic, retain) IBOutlet UITextField *field4;
  20. - (NSString *)dataFilePath;
  21. - (void)applicationWillResignActive:(NSNotification *)notification;
  22. @end
  1. //
  2. //  Persistence3ViewController.m
  3. //  Persistence3
  4. //
  5. //  Created by liu lavy on 11-10-3.
  6. //  Copyright 2011 __MyCompanyName__. All rights reserved.
  7. //
  8. #import "Persistence3ViewController.h"
  9. #import <sqlite3.h>
  10. @implementation Persistence3ViewController
  11. @synthesize field1;
  12. @synthesize field2;
  13. @synthesize field3;
  14. @synthesize field4;
  15. //数据文件的完整路径
  16. - (NSString *)dataFilePath {
  17. //检索Documents目录路径。第二个参数表示将搜索限制在我们的应用程序沙盒中
  18. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  19. //每个应用程序只有一个Documents目录
  20. NSString *documentsDirectory = [paths objectAtIndex:0];
  21. //创建文件名
  22. return [documentsDirectory stringByAppendingPathComponent:kFilename];
  23. }
  24. //应用程序退出时,将数据保存到属性列表文件
  25. - (void)applicationWillResignActive:(NSNotification *)notification {
  26. sqlite3 *database;
  27. if(sqlite3_open([[self dataFilePath] UTF8String], &database) != SQLITE_OK) {
  28. sqlite3_close(database);
  29. NSAssert(0, @"Failed to open database");
  30. }
  31. for(int i = 1; i <= 4; i++) {
  32. NSString *fieldname = [[NSString alloc] initWithFormat:@"field%d", i];
  33. UITextField *field = [self valueForKey:fieldname];
  34. [fieldname release];
  35. char *update = "INSERT OR REPLACE INTO FIELDS (ROW, FIELD_DATA) VALUES (?, ?);";
  36. sqlite3_stmt *stmt;
  37. //将SQL语句编译为sqlite内部一个结构体(sqlite3_stmt),类似java JDBC的PreparedStatement预编译
  38. if (sqlite3_prepare_v2(database, update, -1, &stmt, nil) == SQLITE_OK) {
  39. //在bind参数的时候,参数列表的index从1开始,而取出数据的时候,列的index是从0开始
  40. sqlite3_bind_int(stmt, 1, i);
  41. sqlite3_bind_text(stmt, 2, [field.text UTF8String], -1, NULL);
  42. } else {
  43. NSAssert(0, @"Error:Failed to prepare statemen");
  44. }
  45. //执行SQL文,获取结果
  46. int result = sqlite3_step(stmt);
  47. if(result != SQLITE_DONE) {
  48. NSAssert1(0, @"Error updating table: %d", result);
  49. }
  50. //释放stmt占用的内存(sqlite3_prepare_v2()分配的)
  51. sqlite3_finalize(stmt);
  52. }
  53. sqlite3_close(database);
  54. }
  55. /*
  56. // The designated initializer. Override to perform setup that is required before the view is loaded.
  57. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
  58. self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
  59. if (self) {
  60. // Custom initialization
  61. }
  62. return self;
  63. }
  64. */
  65. /*
  66. // Implement loadView to create a view hierarchy programmatically, without using a nib.
  67. - (void)loadView {
  68. }
  69. */
  70. // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
  71. - (void)viewDidLoad {
  72. [super viewDidLoad];
  73. NSString *filePath = [self dataFilePath];
  74. //检查数据文件是否存在
  75. if([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
  76. //打开数据库
  77. sqlite3 *database;
  78. if(sqlite3_open([filePath UTF8String], &database) != SQLITE_OK) {
  79. sqlite3_close(database);
  80. NSAssert(0, @"Failed to open database");
  81. }
  82. //创建表
  83. char *errorMsg;
  84. NSString *createSQL =
  85. @"CREATE TABLE IF NOT EXISTS FIELDS (ROW INTEGER PRIMARY KEY, FIELD_DATA TEXT);";
  86. if(sqlite3_exec(database, [createSQL UTF8String], NULL, NULL, &errorMsg) != SQLITE_OK) {
  87. sqlite3_close(database);
  88. NSAssert(0, @"Error creating table: %s", errorMsg);
  89. }
  90. //查询
  91. NSString *query = @"SELECT ROW, FIELD_DATA FROM FIELDS ORDER BY ROW";
  92. sqlite3_stmt *statement;
  93. //设置nByte可以加速操作
  94. if(sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, nil) == SQLITE_OK) {
  95. while (sqlite3_step(statement) == SQLITE_ROW) {//返回每一行
  96. int row = sqlite3_column_int(statement, 0);
  97. char *rowData = (char *)sqlite3_column_text(statement, 1);
  98. NSString *fieldName = [[NSString alloc] initWithFormat:@"field%d", row];
  99. NSString *fieldValue = [[NSString alloc] initWithUTF8String:rowData];
  100. UITextField *field = [self valueForKey:fieldName];
  101. field.text = fieldValue;
  102. [fieldName release];
  103. [fieldValue release];
  104. }
  105. //释放statement占用的内存(sqlite3_prepare()分配的)
  106. sqlite3_finalize(statement);
  107. }
  108. sqlite3_close(database);
  109. }
  110. UIApplication *app = [UIApplication sharedApplication];
  111. [[NSNotificationCenter defaultCenter] addObserver:self
  112. selector:@selector(applicationWillResignActive:)
  113. name:UIApplicationWillResignActiveNotification
  114. object:app];
  115. [super viewDidLoad];
  116. }
  117. /*
  118. // Override to allow orientations other than the default portrait orientation.
  119. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
  120. // Return YES for supported orientations
  121. return (interfaceOrientation == UIInterfaceOrientationPortrait);
  122. }
  123. */
  124. - (void)didReceiveMemoryWarning {
  125. // Releases the view if it doesn't have a superview.
  126. [super didReceiveMemoryWarning];
  127. // Release any cached data, images, etc that aren't in use.
  128. }
  129. - (void)viewDidUnload {
  130. self.field1 = nil;
  131. self.field2 = nil;
  132. self.field3 = nil;
  133. self.field4 = nil;
  134. [super viewDidUnload];
  135. }
  136. - (void)dealloc {
  137. [field1 release];
  138. [field2 release];
  139. [field3 release];
  140. [field4 release];
  141. [super dealloc];
  142. }
  143. @end

===================================================================================

===================================================================================

4、Core Data

  1. //
  2. //  PersistenceViewController.h
  3. //  Persistence4
  4. //
  5. //  Created by liu lavy on 11-10-3.
  6. //  Copyright 2011 __MyCompanyName__. All rights reserved.
  7. //
  8. #import <UIKit/UIKit.h>
  9. @interface PersistenceViewController : UIViewController {
  10. UITextField *filed1;
  11. UITextField *field2;
  12. UITextField *field3;
  13. UITextField *field4;
  14. }
  15. @property (nonatomic, retain) IBOutlet UITextField *field1;
  16. @property (nonatomic, retain) IBOutlet UITextField *field2;
  17. @property (nonatomic, retain) IBOutlet UITextField *field3;
  18. @property (nonatomic, retain) IBOutlet UITextField *field4;
  19. @end
  1. //
  2. //  PersistenceViewController.m
  3. //  Persistence4
  4. //
  5. //  Created by liu lavy on 11-10-3.
  6. //  Copyright 2011 __MyCompanyName__. All rights reserved.
  7. //
  8. #import "PersistenceViewController.h"
  9. #import "Persistence4AppDelegate.h"
  10. @implementation PersistenceViewController
  11. @synthesize field1;
  12. @synthesize field2;
  13. @synthesize field3;
  14. @synthesize field4;
  15. -(void) applicationWillResignActive:(NSNotification *)notification {
  16. Persistence4AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
  17. NSManagedObjectContext *context = [appDelegate managedObjectContext];
  18. NSError *error;
  19. for(int i = 1; i <= 4; i++) {
  20. NSString *fieldName = [NSString stringWithFormat:@"field%d", i];
  21. UITextField *theField = [self valueForKey:fieldName];
  22. //创建提取请求
  23. NSFetchRequest *request = [[NSFetchRequest alloc] init];
  24. //创建实体描述并关联到请求
  25. NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Line"
  26. inManagedObjectContext:context];
  27. [request setEntity:entityDescription];
  28. //设置检索数据的条件
  29. NSPredicate *pred = [NSPredicate predicateWithFormat:@"(lineNum = %d)", i];
  30. [request setPredicate:pred];
  31. NSManagedObject *theLine = nil;
  32. ////检查是否返回了标准匹配的对象,如果有则加载它,如果没有则创建一个新的托管对象来保存此字段的文本
  33. NSArray *objects = [context executeFetchRequest:request error:&error];
  34. if(!objects) {
  35. NSLog(@"There was an error");
  36. }
  37. //if(objects.count > 0) {
  38. //  theLine = [objects objectAtIndex:0];
  39. //} else {
  40. //创建一个新的托管对象来保存此字段的文本
  41. theLine = [NSEntityDescription insertNewObjectForEntityForName:@"Line"
  42. inManagedObjectContext:context];
  43. [theLine setValue:[NSNumber numberWithInt:i] forKey:@"lineNum"];
  44. [theLine setValue:theField.text forKey:@"lineText"];
  45. //}
  46. [request release];
  47. }
  48. //通知上下文保存更改
  49. [context save:&error];
  50. }
  51. // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
  52. /*
  53. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
  54. self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
  55. if (self) {
  56. // Custom initialization.
  57. }
  58. return self;
  59. }
  60. */
  61. // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
  62. - (void)viewDidLoad {
  63. Persistence4AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
  64. NSManagedObjectContext *context = [appDelegate managedObjectContext];
  65. //创建一个实体描述
  66. NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Line" inManagedObjectContext:context];
  67. //创建一个请求,用于提取对象
  68. NSFetchRequest *request = [[NSFetchRequest alloc] init];
  69. [request setEntity:entityDescription];
  70. //检索对象
  71. NSError *error;
  72. NSArray *objects = [context executeFetchRequest:request error:&error];
  73. if(!objects) {
  74. NSLog(@"There was an error!");
  75. }
  76. for(NSManagedObject *obj in objects) {
  77. NSNumber *lineNum = [obj valueForKey:@"lineNum"];
  78. NSString *lineText = [obj valueForKey:@"lineText"];
  79. NSString *fieldName = [NSString stringWithFormat:@"field%d", [lineNum integerValue]];
  80. UITextField *textField = [self valueForKey:fieldName];
  81. textField.text = lineText;
  82. }
  83. [request release];
  84. UIApplication *app = [UIApplication sharedApplication];
  85. [[NSNotificationCenter defaultCenter] addObserver:self
  86. selector:@selector(applicationWillResignActive:)
  87. name:UIApplicationWillResignActiveNotification
  88. object:app];
  89. [super viewDidLoad];
  90. }
  91. /*
  92. // Override to allow orientations other than the default portrait orientation.
  93. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
  94. // Return YES for supported orientations.
  95. return (interfaceOrientation == UIInterfaceOrientationPortrait);
  96. }
  97. */
  98. - (void)didReceiveMemoryWarning {
  99. // Releases the view if it doesn't have a superview.
  100. [super didReceiveMemoryWarning];
  101. // Release any cached data, images, etc. that aren't in use.
  102. }
  103. - (void)viewDidUnload {
  104. self.field1 = nil;
  105. self.field2 = nil;
  106. self.field3 = nil;
  107. self.field4 = nil;
  108. [super viewDidUnload];
  109. }
  110. - (void)dealloc {
  111. [field1 release];
  112. [field2 release];
  113. [field3 release];
  114. [field4 release];
  115. [super dealloc];
  116. }
  117. @end

5、AppSettings

  1. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

===================================================================================

===================================================================================

6、普通文件存储

这种方式即自己将数据通过IO保存到文件,或从文件读取。

声明:此篇所有代码来自《Iphone4与IPad开发基础教程》

IOS 数据储存的更多相关文章

  1. iOS 数据储存--SQLite 操作数据库-FMDB,sqlite数据类型,保存图片,demo

    1.SQLite 语句中 数据类型的储存 /* 不区分大小写 char(长度).字符串 NULL. 空值 INTEGER. 整型 REAL.浮点型 TEXT.文本类型 BLOB. 二进制类型,用来存储 ...

  2. iOS数据存储

    [reference]http://www.infoq.com/cn/articles/data-storage-in-ios 谈到数据储存,首先要明确区分两个概念,数据结构和储存方式.所谓数据结构就 ...

  3. 面试题汇总--数据储存/应用程序/UI控件/客户端的安全性与框架处理。。。

    一 数据储存  1.如果后期需要增加数据库中的字段怎么实现,如果不使用 CoreData 呢?编写 SQL 语句来操作原来表中的字段1)增加表字段ALTER TABLE 表名 ADD COLUMN 字 ...

  4. 关于JAVA数据储存

    关于JAVA数据储存: 在JAVA中,有六个不同的地方可以存储数据: 1. 寄存器(register) 这是最快的存储区,因为它位于不同于其他存储区的地方--处理器内部.但是寄存器的数量极其有限,所以 ...

  5. Android下的数据储存方式(三)

      Android下最好的数据储存方式:关系型数据库sqlite.   数据库的创建:使用SqliteOpenHelper类 结合SqliteOpenHelper类和SQLiteDatabase类的帮 ...

  6. Android下的数据储存方式( 二)

    在上一篇文章中我们介绍了SharedPreferences的使用方法. 今天我们继续介绍另一种储存数据的方式:使用内部储存和外部储存 每一个Android设备都拥有两个数据储存区域:外部储存和外部储存 ...

  7. Android下的数据储存方式

      安卓系统默认提供了一下几种数据储存的方式: Shared Preferences 内部储存 外部储存 SQLite数据库 保存到网络服务器   使用Shared Preferences       ...

  8. iOS数据持久化-OC

    沙盒详解 1.IOS沙盒机制 IOS应用程序只能在为该改程序创建的文件系统中读取文件,不可以去其它地方访问,此区域被成为沙盒,所以所有的非代码文件都要保存在此,例如图像,图标,声音,映像,属性列表,文 ...

  9. iOS 数据持久化(扩展知识:模糊背景效果和密码保护功能)

    本篇随笔除了介绍 iOS 数据持久化知识之外,还贯穿了以下内容: (1)自定义 TableView,结合 block 从 ViewController 中分离出 View,轻 ViewControll ...

随机推荐

  1. Roads in the North (树的直径)

    Building and maintaining roads among communities in the far North is an expensive business. With thi ...

  2. 利用递归方法实现链表反转、前N个节点反转以及中间部分节点反转

    一.反转整个链表 问题:定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点. 示例: 输入: 1->2->3->4->5->NULL 输出: 5-&g ...

  3. 11 vue 自定义全局方法

    //global.js// 定义vue 全局方   // 定义vue 全局方法 建议自定义的全局方法加_ 以示区分 export default {   install(Vue, options =  ...

  4. day48:django前戏之HTTP协议&自定义web框架

    目录 1.HTTP协议 1.HTTP协议简介 2.HTTP协议概述 3.HTTP协议工作原理 4.HTTP协议请求方法 5.HTTP协议状态码 6.URL 7.HTTP请求格式 8.HTTP响应格式 ...

  5. Splay 记录

    luogu 模板 P3391 [模板]文艺平衡树(Splay). 知识点:1.splay模板题,练习splay,rotate顺序:x变成z的儿子,x的一个儿子变为y的一个儿子(具体哪个看代码),y变为 ...

  6. opencv-python函数

    opencv-python读取.展示和存储图像 1.imshow函数 imshow函数作用是在窗口中显示图像,窗口自动适合于图像大小,我们也可以通过imutils模块调整显示图像的窗口的大小.函数官方 ...

  7. leetcode刷题-46全排列

    题目 给定一个 没有重复 数字的序列,返回其所有可能的全排列. 思路 回溯算法 不断取出字符,对剩余字符进行选择 实现 class Solution: def permute(self, nums: ...

  8. 深入理解 vue 中 scoped 样式作用域的规则

    哈喽!大家好!我是木瓜太香,今天我们来聊一个 vue 的样式作用域的问题,通常我们开发项目的时候是要在 style 上加上 scoped 来起到规定组件作用域的效果的,所以了解他们的规则也是很有必要的 ...

  9. nmap端口扫描工具下载和安装使用

    1.下载地址 https://nmap.org/download.html 2.下载之后进行安装 选择I Agree 后,建议全选,特别是zenmap,这个是图形化界面,不喜欢命令行格式的可以用zen ...

  10. git仓库下拉和上传

    git仓库比较方便,可以实现白天在公司写的代码,下班之前上传到git仓库,晚上在另一台电脑上直接下拉下来,其实感觉和开发用的svn差不多 在另一篇博客里面写到,需要先在git里面新增好仓库和成员之后, ...