IOS 数据存储

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

属性列表

对象归档

SQLite3

CoreData

AppSettings

普通文件存储

1、属性列表

[cpp]  view plain copy
  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.   
  9. #import <UIKit/UIKit.h>  
  10. #define kFilename @"data.plist"  
  11.   
  12. @interface Persistence1ViewController : UIViewController {  
  13.     UITextField *filed1;  
  14.     UITextField *field2;  
  15.     UITextField *field3;  
  16.     UITextField *field4;  
  17. }  
  18. @property (nonatomic, retain) IBOutlet UITextField *field1;  
  19. @property (nonatomic, retain) IBOutlet UITextField *field2;  
  20. @property (nonatomic, retain) IBOutlet UITextField *field3;  
  21. @property (nonatomic, retain) IBOutlet UITextField *field4;  
  22.   
  23. - (NSString *)dataFilePath;  
  24. - (void)applicationWillResignActive:(NSNotification *)notification;  
  25.   
  26. @end  

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

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

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

2、对象归档

[cpp]  view plain copy
  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.   
  9. #import <Foundation/Foundation.h>  
  10.   
  11. @interface Fourlines : NSObject <NSCoding, NSCopying> {  
  12.     NSString *field1;  
  13.     NSString *field2;  
  14.     NSString *field3;  
  15.     NSString *field4;  
  16. }  
  17. @property (nonatomic, retain) NSString *field1;  
  18. @property (nonatomic, retain) NSString *field2;  
  19. @property (nonatomic, retain) NSString *field3;  
  20. @property (nonatomic, retain) NSString *field4;  
  21.   
  22.   
  23. @end  

[cpp]  view plain copy
  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.   
  9. #import "Fourlines.h"  
  10.   
  11. #define kField1Key @"Field1"  
  12. #define kField2Key @"Field2"  
  13. #define kField3Key @"Field3"  
  14. #define kField4Key @"Field4"  
  15.   
  16. @implementation Fourlines  
  17. @synthesize field1;  
  18. @synthesize field2;  
  19. @synthesize field3;  
  20. @synthesize field4;  
  21.   
  22. #pragma mark NSCoding  
  23. - (void)encodeWithCoder:(NSCoder *)aCoder {  
  24.     [aCoder encodeObject:field1 forKey:kField1Key];  
  25.     [aCoder encodeObject:field2 forKey:kField2Key];  
  26.     [aCoder encodeObject:field3 forKey:kField3Key];  
  27.     [aCoder encodeObject:field4 forKey:kField4Key];  
  28. }  
  29.   
  30. -(id) initWithCoder:(NSCoder *)aDecoder {  
  31.     if(self = [super init]) {  
  32.         field1 = [[aDecoder decodeObjectForKey:kField1Key] retain];  
  33.         field2 = [[aDecoder decodeObjectForKey:kField2Key] retain];  
  34.         field3 = [[aDecoder decodeObjectForKey:kField3Key] retain];  
  35.         field4 = [[aDecoder decodeObjectForKey:kField4Key] retain];  
  36.     }  
  37.     return self;  
  38. }  
  39.   
  40. #pragma mark -  
  41. #pragma mark NSCopying  
  42. - (id) copyWithZone:(NSZone *)zone {  
  43.     Fourlines *copy = [[[self class] allocWithZone: zone] init];  
  44.     copy.field1 = [[self.field1 copyWithZone: zone] autorelease];  
  45.     copy.field2 = [[self.field2 copyWithZone: zone] autorelease];  
  46.     copy.field3 = [[self.field3 copyWithZone: zone] autorelease];  
  47.     copy.field4 = [[self.field4 copyWithZone: zone] autorelease];  
  48.     return copy;  
  49. }  
  50. @end  

[cpp]  view plain copy
  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.   
  9. #import <UIKit/UIKit.h>  
  10. #define kFilename @"archive"  
  11. #define kDataKey @"Data"  
  12.   
  13. @interface Persistence2ViewController : UIViewController {  
  14.     UITextField *filed1;  
  15.     UITextField *field2;  
  16.     UITextField *field3;  
  17.     UITextField *field4;  
  18. }  
  19. @property (nonatomic, retain) IBOutlet UITextField *field1;  
  20. @property (nonatomic, retain) IBOutlet UITextField *field2;  
  21. @property (nonatomic, retain) IBOutlet UITextField *field3;  
  22. @property (nonatomic, retain) IBOutlet UITextField *field4;  
  23.   
  24. - (NSString *)dataFilePath;  
  25. - (void)applicationWillResignActive:(NSNotification *)notification;  
  26.   
  27. @end  

[cpp]  view plain copy
  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.   
  9. #import "Persistence2ViewController.h"  
  10. #import "Fourlines.h"  
  11.   
  12. @implementation Persistence2ViewController  
  13. @synthesize field1;  
  14. @synthesize field2;  
  15. @synthesize field3;  
  16. @synthesize field4;  
  17.   
  18. //数据文件的完整路径  
  19. - (NSString *)dataFilePath {  
  20.     //检索Documents目录路径。第二个参数表示将搜索限制在我们的应用程序沙盒中  
  21.     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
  22.     //每个应用程序只有一个Documents目录  
  23.     NSString *documentsDirectory = [paths objectAtIndex:0];  
  24.     //创建文件名  
  25.     return [documentsDirectory stringByAppendingPathComponent:kFilename];  
  26. }  
  27.   
  28. //应用程序退出时,将数据保存到属性列表文件  
  29. - (void)applicationWillResignActive:(NSNotification *)notification {  
  30.     Fourlines *fourlines = [[Fourlines alloc] init];  
  31.     fourlines.field1 = field1.text;  
  32.     fourlines.field2 = field2.text;  
  33.     fourlines.field3 = field3.text;  
  34.     fourlines.field4 = field4.text;  
  35.       
  36.     NSMutableData *data = [[NSMutableData alloc] init];//用于存储编码的数据  
  37.     NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];  
  38.       
  39.     [archiver encodeObject:fourlines forKey:kDataKey];  
  40.     [archiver finishEncoding];  
  41.     [data writeToFile:[self dataFilePath] atomically:YES];  
  42.       
  43.     [fourlines release];  
  44.     [archiver release];  
  45.     [data release];  
  46. }  
  47.   
  48. /* 
  49.  // The designated initializer. Override to perform setup that is required before the view is loaded. 
  50.  - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { 
  51.  self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
  52.  if (self) { 
  53.  // Custom initialization 
  54.  } 
  55.  return self; 
  56.  } 
  57.  */  
  58.   
  59. /* 
  60.  // Implement loadView to create a view hierarchy programmatically, without using a nib. 
  61.  - (void)loadView { 
  62.  } 
  63.  */  
  64.   
  65.   
  66.   
  67. // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.  
  68. - (void)viewDidLoad {  
  69.     [super viewDidLoad];  
  70.     NSString *filePath = [self dataFilePath];  
  71.     //检查数据文件是否存在  
  72.     if([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {  
  73.           
  74.         //从文件获取用于解码的数据  
  75.         NSData *data = [[NSMutableData alloc] initWithContentsOfFile:[self dataFilePath]];  
  76.         NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];  
  77.           
  78.         Fourlines *fourlines = [unarchiver decodeObjectForKey:kDataKey];  
  79.         [unarchiver finishDecoding];  
  80.           
  81.         field1.text = fourlines.field1;  
  82.         field2.text = fourlines.field2;  
  83.         field3.text = fourlines.field3;  
  84.         field4.text = fourlines.field4;  
  85.           
  86.         [unarchiver release];  
  87.         [data release];  
  88.     }  
  89.     UIApplication *app = [UIApplication sharedApplication];  
  90.     [[NSNotificationCenter defaultCenter] addObserver:self  
  91.                                              selector:@selector(applicationWillResignActive:)  
  92.                                              name:UIApplicationWillResignActiveNotification  
  93.                                              object:app];  
  94.     [super viewDidLoad];  
  95. }  
  96.   
  97.   
  98. /* 
  99.  // Override to allow orientations other than the default portrait orientation. 
  100.  - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { 
  101.  // Return YES for supported orientations 
  102.  return (interfaceOrientation == UIInterfaceOrientationPortrait); 
  103.  } 
  104.  */  
  105.   
  106. - (void)didReceiveMemoryWarning {  
  107.     // Releases the view if it doesn't have a superview.  
  108.     [super didReceiveMemoryWarning];  
  109.       
  110.     // Release any cached data, images, etc that aren't in use.  
  111. }  
  112.   
  113. - (void)viewDidUnload {  
  114.     self.field1 = nil;  
  115.     self.field2 = nil;  
  116.     self.field3 = nil;  
  117.     self.field4 = nil;  
  118.     [super viewDidUnload];  
  119. }  
  120.   
  121.   
  122. - (void)dealloc {  
  123.     [field1 release];  
  124.     [field2 release];  
  125.     [field3 release];  
  126.     [field4 release];  
  127.     [super dealloc];  
  128. }  
  129. @end  


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

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


3、SQLite

[cpp]  view plain copy
  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.   
  9. #import <UIKit/UIKit.h>  
  10. #define kFilename @"data.sqlite3"  
  11.   
  12. @interface Persistence3ViewController : UIViewController {  
  13.     UITextField *filed1;  
  14.     UITextField *field2;  
  15.     UITextField *field3;  
  16.     UITextField *field4;  
  17. }  
  18. @property (nonatomic, retain) IBOutlet UITextField *field1;  
  19. @property (nonatomic, retain) IBOutlet UITextField *field2;  
  20. @property (nonatomic, retain) IBOutlet UITextField *field3;  
  21. @property (nonatomic, retain) IBOutlet UITextField *field4;  
  22.   
  23. - (NSString *)dataFilePath;  
  24. - (void)applicationWillResignActive:(NSNotification *)notification;  
  25. @end  

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

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

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

4、Core Data

[cpp]  view plain copy
  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.   
  9. #import <UIKit/UIKit.h>  
  10.   
  11.   
  12. @interface PersistenceViewController : UIViewController {  
  13.     UITextField *filed1;  
  14.     UITextField *field2;  
  15.     UITextField *field3;  
  16.     UITextField *field4;  
  17. }  
  18. @property (nonatomic, retain) IBOutlet UITextField *field1;  
  19. @property (nonatomic, retain) IBOutlet UITextField *field2;  
  20. @property (nonatomic, retain) IBOutlet UITextField *field3;  
  21. @property (nonatomic, retain) IBOutlet UITextField *field4;  
  22.   
  23. @end  

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

5、AppSettings

[cpp]  view plain copy
  1. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];  

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

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

6、普通文件存储

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


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

from:http://blog.csdn.net/liuhongwei123888/article/details/6841338
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值