`
mmdev
  • 浏览: 12933149 次
  • 性别: Icon_minigender_1
  • 来自: 大连
文章分类
社区版块
存档分类
最新评论

IOS 数据存储

 
阅读更多
ios数据存储包括以下几种存储机制:

属性列表

对象归档

SQLite3

CoreData

AppSettings

普通文件存储

1、属性列表

  1. //
  2. //Persistence1ViewController.h
  3. //Persistence1
  4. //
  5. //Createdbyliulavyon11-10-3.
  6. //Copyright2011__MyCompanyName__.Allrightsreserved.
  7. //
  8. #import<UIKit/UIKit.h>
  9. #definekFilename@"data.plist"
  10. @interfacePersistence1ViewController:UIViewController{
  11. UITextField*filed1;
  12. UITextField*field2;
  13. UITextField*field3;
  14. UITextField*field4;
  15. }
  16. @property(nonatomic,retain)IBOutletUITextField*field1;
  17. @property(nonatomic,retain)IBOutletUITextField*field2;
  18. @property(nonatomic,retain)IBOutletUITextField*field3;
  19. @property(nonatomic,retain)IBOutletUITextField*field4;
  20. -(NSString*)dataFilePath;
  21. -(void)applicationWillResignActive:(NSNotification*)notification;
  22. @end

  1. //
  2. //Persistence1ViewController.m
  3. //Persistence1
  4. //
  5. //Createdbyliulavyon11-10-3.
  6. //Copyright2011__MyCompanyName__.Allrightsreserved.
  7. //
  8. #import"Persistence1ViewController.h"
  9. @implementationPersistence1ViewController
  10. @synthesizefield1;
  11. @synthesizefield2;
  12. @synthesizefield3;
  13. @synthesizefield4;
  14. //数据文件的完整路径
  15. -(NSString*)dataFilePath{
  16. //检索Documents目录路径。第二个参数表示将搜索限制在我们的应用程序沙盒中
  17. NSArray*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
  18. //每个应用程序只有一个Documents目录
  19. NSString*documentsDirectory=[pathsobjectAtIndex:0];
  20. //创建文件名
  21. return[documentsDirectorystringByAppendingPathComponent:kFilename];
  22. }
  23. //应用程序退出时,将数据保存到属性列表文件
  24. -(void)applicationWillResignActive:(NSNotification*)notification{
  25. NSMutableArray*array=[[NSMutableArrayalloc]init];
  26. [arrayaddObject:field1.text];
  27. [arrayaddObject:field2.text];
  28. [arrayaddObject:field3.text];
  29. [arrayaddObject:field4.text];
  30. [arraywriteToFile:[selfdataFilePath]atomically:YES];
  31. [arrayrelease];
  32. }
  33. /*
  34. //Thedesignatedinitializer.Overridetoperformsetupthatisrequiredbeforetheviewisloaded.
  35. -(id)initWithNibName:(NSString*)nibNameOrNilbundle:(NSBundle*)nibBundleOrNil{
  36. self=[superinitWithNibName:nibNameOrNilbundle:nibBundleOrNil];
  37. if(self){
  38. //Custominitialization
  39. }
  40. returnself;
  41. }
  42. */
  43. /*
  44. //ImplementloadViewtocreateaviewhierarchyprogrammatically,withoutusinganib.
  45. -(void)loadView{
  46. }
  47. */
  48. //ImplementviewDidLoadtodoadditionalsetupafterloadingtheview,typicallyfromanib.
  49. -(void)viewDidLoad{
  50. [superviewDidLoad];
  51. NSString*filePath=[selfdataFilePath];
  52. //检查数据文件是否存在
  53. if([[NSFileManagerdefaultManager]fileExistsAtPath:filePath]){
  54. NSArray*array=[[NSArrayalloc]initWithContentsOfFile:filePath];
  55. field1.text=[arrayobjectAtIndex:0];
  56. field2.text=[arrayobjectAtIndex:1];
  57. field3.text=[arrayobjectAtIndex:2];
  58. field4.text=[arrayobjectAtIndex:3];
  59. [arrayrelease];
  60. }
  61. UIApplication*app=[UIApplicationsharedApplication];
  62. [[NSNotificationCenterdefaultCenter]addObserver:self
  63. selector:@selector(applicationWillResignActive:)
  64. name:UIApplicationWillResignActiveNotification
  65. object:app];
  66. [superviewDidLoad];
  67. }
  68. /*
  69. //Overridetoalloworientationsotherthanthedefaultportraitorientation.
  70. -(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
  71. //ReturnYESforsupportedorientations
  72. return(interfaceOrientation==UIInterfaceOrientationPortrait);
  73. }
  74. */
  75. -(void)didReceiveMemoryWarning{
  76. //Releasestheviewifitdoesn'thaveasuperview.
  77. [superdidReceiveMemoryWarning];
  78. //Releaseanycacheddata,images,etcthataren'tinuse.
  79. }
  80. -(void)viewDidUnload{
  81. self.field1=nil;
  82. self.field2=nil;
  83. self.field3=nil;
  84. self.field4=nil;
  85. [superviewDidUnload];
  86. }
  87. -(void)dealloc{
  88. [field1release];
  89. [field2release];
  90. [field3release];
  91. [field4release];
  92. [superdealloc];
  93. }
  94. @end

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

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

2、对象归档

  1. //
  2. //Fourlines.h
  3. //Persistence2
  4. //
  5. //Createdbyliulavyon11-10-3.
  6. //Copyright2011__MyCompanyName__.Allrightsreserved.
  7. //
  8. #import<Foundation/Foundation.h>
  9. @interfaceFourlines: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. //Createdbyliulavyon11-10-3.
  6. //Copyright2011__MyCompanyName__.Allrightsreserved.
  7. //
  8. #import"Fourlines.h"
  9. #definekField1Key@"Field1"
  10. #definekField2Key@"Field2"
  11. #definekField3Key@"Field3"
  12. #definekField4Key@"Field4"
  13. @implementationFourlines
  14. @synthesizefield1;
  15. @synthesizefield2;
  16. @synthesizefield3;
  17. @synthesizefield4;
  18. #pragmamarkNSCoding
  19. -(void)encodeWithCoder:(NSCoder*)aCoder{
  20. [aCoderencodeObject:field1forKey:kField1Key];
  21. [aCoderencodeObject:field2forKey:kField2Key];
  22. [aCoderencodeObject:field3forKey:kField3Key];
  23. [aCoderencodeObject:field4forKey:kField4Key];
  24. }
  25. -(id)initWithCoder:(NSCoder*)aDecoder{
  26. if(self=[superinit]){
  27. field1=[[aDecoderdecodeObjectForKey:kField1Key]retain];
  28. field2=[[aDecoderdecodeObjectForKey:kField2Key]retain];
  29. field3=[[aDecoderdecodeObjectForKey:kField3Key]retain];
  30. field4=[[aDecoderdecodeObjectForKey:kField4Key]retain];
  31. }
  32. returnself;
  33. }
  34. #pragmamark-
  35. #pragmamarkNSCopying
  36. -(id)copyWithZone:(NSZone*)zone{
  37. Fourlines*copy=[[[selfclass]allocWithZone:zone]init];
  38. copy.field1=[[self.field1copyWithZone:zone]autorelease];
  39. copy.field2=[[self.field2copyWithZone:zone]autorelease];
  40. copy.field3=[[self.field3copyWithZone:zone]autorelease];
  41. copy.field4=[[self.field4copyWithZone:zone]autorelease];
  42. returncopy;
  43. }
  44. @end

  1. //
  2. //Persistence2ViewController.h
  3. //Persistence2
  4. //
  5. //Createdbyliulavyon11-10-3.
  6. //Copyright2011__MyCompanyName__.Allrightsreserved.
  7. //
  8. #import<UIKit/UIKit.h>
  9. #definekFilename@"archive"
  10. #definekDataKey@"Data"
  11. @interfacePersistence2ViewController:UIViewController{
  12. UITextField*filed1;
  13. UITextField*field2;
  14. UITextField*field3;
  15. UITextField*field4;
  16. }
  17. @property(nonatomic,retain)IBOutletUITextField*field1;
  18. @property(nonatomic,retain)IBOutletUITextField*field2;
  19. @property(nonatomic,retain)IBOutletUITextField*field3;
  20. @property(nonatomic,retain)IBOutletUITextField*field4;
  21. -(NSString*)dataFilePath;
  22. -(void)applicationWillResignActive:(NSNotification*)notification;
  23. @end

  1. //
  2. //Persistence2ViewController.m
  3. //Persistence2
  4. //
  5. //Createdbyliulavyon11-10-3.
  6. //Copyright2011__MyCompanyName__.Allrightsreserved.
  7. //
  8. #import"Persistence2ViewController.h"
  9. #import"Fourlines.h"
  10. @implementationPersistence2ViewController
  11. @synthesizefield1;
  12. @synthesizefield2;
  13. @synthesizefield3;
  14. @synthesizefield4;
  15. //数据文件的完整路径
  16. -(NSString*)dataFilePath{
  17. //检索Documents目录路径。第二个参数表示将搜索限制在我们的应用程序沙盒中
  18. NSArray*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
  19. //每个应用程序只有一个Documents目录
  20. NSString*documentsDirectory=[pathsobjectAtIndex:0];
  21. //创建文件名
  22. return[documentsDirectorystringByAppendingPathComponent:kFilename];
  23. }
  24. //应用程序退出时,将数据保存到属性列表文件
  25. -(void)applicationWillResignActive:(NSNotification*)notification{
  26. Fourlines*fourlines=[[Fourlinesalloc]init];
  27. fourlines.field1=field1.text;
  28. fourlines.field2=field2.text;
  29. fourlines.field3=field3.text;
  30. fourlines.field4=field4.text;
  31. NSMutableData*data=[[NSMutableDataalloc]init];//用于存储编码的数据
  32. NSKeyedArchiver*archiver=[[NSKeyedArchiveralloc]initForWritingWithMutableData:data];
  33. [archiverencodeObject:fourlinesforKey:kDataKey];
  34. [archiverfinishEncoding];
  35. [datawriteToFile:[selfdataFilePath]atomically:YES];
  36. [fourlinesrelease];
  37. [archiverrelease];
  38. [datarelease];
  39. }
  40. /*
  41. //Thedesignatedinitializer.Overridetoperformsetupthatisrequiredbeforetheviewisloaded.
  42. -(id)initWithNibName:(NSString*)nibNameOrNilbundle:(NSBundle*)nibBundleOrNil{
  43. self=[superinitWithNibName:nibNameOrNilbundle:nibBundleOrNil];
  44. if(self){
  45. //Custominitialization
  46. }
  47. returnself;
  48. }
  49. */
  50. /*
  51. //ImplementloadViewtocreateaviewhierarchyprogrammatically,withoutusinganib.
  52. -(void)loadView{
  53. }
  54. */
  55. //ImplementviewDidLoadtodoadditionalsetupafterloadingtheview,typicallyfromanib.
  56. -(void)viewDidLoad{
  57. [superviewDidLoad];
  58. NSString*filePath=[selfdataFilePath];
  59. //检查数据文件是否存在
  60. if([[NSFileManagerdefaultManager]fileExistsAtPath:filePath]){
  61. //从文件获取用于解码的数据
  62. NSData*data=[[NSMutableDataalloc]initWithContentsOfFile:[selfdataFilePath]];
  63. NSKeyedUnarchiver*unarchiver=[[NSKeyedUnarchiveralloc]initForReadingWithData:data];
  64. Fourlines*fourlines=[unarchiverdecodeObjectForKey:kDataKey];
  65. [unarchiverfinishDecoding];
  66. field1.text=fourlines.field1;
  67. field2.text=fourlines.field2;
  68. field3.text=fourlines.field3;
  69. field4.text=fourlines.field4;
  70. [unarchiverrelease];
  71. [datarelease];
  72. }
  73. UIApplication*app=[UIApplicationsharedApplication];
  74. [[NSNotificationCenterdefaultCenter]addObserver:self
  75. selector:@selector(applicationWillResignActive:)
  76. name:UIApplicationWillResignActiveNotification
  77. object:app];
  78. [superviewDidLoad];
  79. }
  80. /*
  81. //Overridetoalloworientationsotherthanthedefaultportraitorientation.
  82. -(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
  83. //ReturnYESforsupportedorientations
  84. return(interfaceOrientation==UIInterfaceOrientationPortrait);
  85. }
  86. */
  87. -(void)didReceiveMemoryWarning{
  88. //Releasestheviewifitdoesn'thaveasuperview.
  89. [superdidReceiveMemoryWarning];
  90. //Releaseanycacheddata,images,etcthataren'tinuse.
  91. }
  92. -(void)viewDidUnload{
  93. self.field1=nil;
  94. self.field2=nil;
  95. self.field3=nil;
  96. self.field4=nil;
  97. [superviewDidUnload];
  98. }
  99. -(void)dealloc{
  100. [field1release];
  101. [field2release];
  102. [field3release];
  103. [field4release];
  104. [superdealloc];
  105. }
  106. @end


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

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


3、SQLite

  1. //
  2. //Persistence3ViewController.h
  3. //Persistence3
  4. //
  5. //Createdbyliulavyon11-10-3.
  6. //Copyright2011__MyCompanyName__.Allrightsreserved.
  7. //
  8. #import<UIKit/UIKit.h>
  9. #definekFilename@"data.sqlite3"
  10. @interfacePersistence3ViewController:UIViewController{
  11. UITextField*filed1;
  12. UITextField*field2;
  13. UITextField*field3;
  14. UITextField*field4;
  15. }
  16. @property(nonatomic,retain)IBOutletUITextField*field1;
  17. @property(nonatomic,retain)IBOutletUITextField*field2;
  18. @property(nonatomic,retain)IBOutletUITextField*field3;
  19. @property(nonatomic,retain)IBOutletUITextField*field4;
  20. -(NSString*)dataFilePath;
  21. -(void)applicationWillResignActive:(NSNotification*)notification;
  22. @end

  1. //
  2. //Persistence3ViewController.m
  3. //Persistence3
  4. //
  5. //Createdbyliulavyon11-10-3.
  6. //Copyright2011__MyCompanyName__.Allrightsreserved.
  7. //
  8. #import"Persistence3ViewController.h"
  9. #import<sqlite3.h>
  10. @implementationPersistence3ViewController
  11. @synthesizefield1;
  12. @synthesizefield2;
  13. @synthesizefield3;
  14. @synthesizefield4;
  15. //数据文件的完整路径
  16. -(NSString*)dataFilePath{
  17. //检索Documents目录路径。第二个参数表示将搜索限制在我们的应用程序沙盒中
  18. NSArray*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
  19. //每个应用程序只有一个Documents目录
  20. NSString*documentsDirectory=[pathsobjectAtIndex:0];
  21. //创建文件名
  22. return[documentsDirectorystringByAppendingPathComponent:kFilename];
  23. }
  24. //应用程序退出时,将数据保存到属性列表文件
  25. -(void)applicationWillResignActive:(NSNotification*)notification{
  26. sqlite3*database;
  27. if(sqlite3_open([[selfdataFilePath]UTF8String],&database)!=SQLITE_OK){
  28. sqlite3_close(database);
  29. NSAssert(0,@"Failedtoopendatabase");
  30. }
  31. for(inti=1;i<=4;i++){
  32. NSString*fieldname=[[NSStringalloc]initWithFormat:@"field%d",i];
  33. UITextField*field=[selfvalueForKey:fieldname];
  34. [fieldnamerelease];
  35. char*update="INSERTORREPLACEINTOFIELDS(ROW,FIELD_DATA)VALUES(?,?);";
  36. sqlite3_stmt*stmt;
  37. //将SQL语句编译为sqlite内部一个结构体(sqlite3_stmt),类似javaJDBC的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.textUTF8String],-1,NULL);
  42. }else{
  43. NSAssert(0,@"Error:Failedtopreparestatemen");
  44. }
  45. //执行SQL文,获取结果
  46. intresult=sqlite3_step(stmt);
  47. if(result!=SQLITE_DONE){
  48. NSAssert1(0,@"Errorupdatingtable:%d",result);
  49. }
  50. //释放stmt占用的内存(sqlite3_prepare_v2()分配的)
  51. sqlite3_finalize(stmt);
  52. }
  53. sqlite3_close(database);
  54. }
  55. /*
  56. //Thedesignatedinitializer.Overridetoperformsetupthatisrequiredbeforetheviewisloaded.
  57. -(id)initWithNibName:(NSString*)nibNameOrNilbundle:(NSBundle*)nibBundleOrNil{
  58. self=[superinitWithNibName:nibNameOrNilbundle:nibBundleOrNil];
  59. if(self){
  60. //Custominitialization
  61. }
  62. returnself;
  63. }
  64. */
  65. /*
  66. //ImplementloadViewtocreateaviewhierarchyprogrammatically,withoutusinganib.
  67. -(void)loadView{
  68. }
  69. */
  70. //ImplementviewDidLoadtodoadditionalsetupafterloadingtheview,typicallyfromanib.
  71. -(void)viewDidLoad{
  72. [superviewDidLoad];
  73. NSString*filePath=[selfdataFilePath];
  74. //检查数据文件是否存在
  75. if([[NSFileManagerdefaultManager]fileExistsAtPath:filePath]){
  76. //打开数据库
  77. sqlite3*database;
  78. if(sqlite3_open([filePathUTF8String],&database)!=SQLITE_OK){
  79. sqlite3_close(database);
  80. NSAssert(0,@"Failedtoopendatabase");
  81. }
  82. //创建表
  83. char*errorMsg;
  84. NSString*createSQL=
  85. @"CREATETABLEIFNOTEXISTSFIELDS(ROWINTEGERPRIMARYKEY,FIELD_DATATEXT);";
  86. if(sqlite3_exec(database,[createSQLUTF8String],NULL,NULL,&errorMsg)!=SQLITE_OK){
  87. sqlite3_close(database);
  88. NSAssert(0,@"Errorcreatingtable:%s",errorMsg);
  89. }
  90. //查询
  91. NSString*query=@"SELECTROW,FIELD_DATAFROMFIELDSORDERBYROW";
  92. sqlite3_stmt*statement;
  93. //设置nByte可以加速操作
  94. if(sqlite3_prepare_v2(database,[queryUTF8String],-1,&statement,nil)==SQLITE_OK){
  95. while(sqlite3_step(statement)==SQLITE_ROW){//返回每一行
  96. introw=sqlite3_column_int(statement,0);
  97. char*rowData=(char*)sqlite3_column_text(statement,1);
  98. NSString*fieldName=[[NSStringalloc]initWithFormat:@"field%d",row];
  99. NSString*fieldValue=[[NSStringalloc]initWithUTF8String:rowData];
  100. UITextField*field=[selfvalueForKey:fieldName];
  101. field.text=fieldValue;
  102. [fieldNamerelease];
  103. [fieldValuerelease];
  104. }
  105. //释放statement占用的内存(sqlite3_prepare()分配的)
  106. sqlite3_finalize(statement);
  107. }
  108. sqlite3_close(database);
  109. }
  110. UIApplication*app=[UIApplicationsharedApplication];
  111. [[NSNotificationCenterdefaultCenter]addObserver:self
  112. selector:@selector(applicationWillResignActive:)
  113. name:UIApplicationWillResignActiveNotification
  114. object:app];
  115. [superviewDidLoad];
  116. }
  117. /*
  118. //Overridetoalloworientationsotherthanthedefaultportraitorientation.
  119. -(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
  120. //ReturnYESforsupportedorientations
  121. return(interfaceOrientation==UIInterfaceOrientationPortrait);
  122. }
  123. */
  124. -(void)didReceiveMemoryWarning{
  125. //Releasestheviewifitdoesn'thaveasuperview.
  126. [superdidReceiveMemoryWarning];
  127. //Releaseanycacheddata,images,etcthataren'tinuse.
  128. }
  129. -(void)viewDidUnload{
  130. self.field1=nil;
  131. self.field2=nil;
  132. self.field3=nil;
  133. self.field4=nil;
  134. [superviewDidUnload];
  135. }
  136. -(void)dealloc{
  137. [field1release];
  138. [field2release];
  139. [field3release];
  140. [field4release];
  141. [superdealloc];
  142. }
  143. @end

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

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

4、Core Data

  1. //
  2. //PersistenceViewController.h
  3. //Persistence4
  4. //
  5. //Createdbyliulavyon11-10-3.
  6. //Copyright2011__MyCompanyName__.Allrightsreserved.
  7. //
  8. #import<UIKit/UIKit.h>
  9. @interfacePersistenceViewController:UIViewController{
  10. UITextField*filed1;
  11. UITextField*field2;
  12. UITextField*field3;
  13. UITextField*field4;
  14. }
  15. @property(nonatomic,retain)IBOutletUITextField*field1;
  16. @property(nonatomic,retain)IBOutletUITextField*field2;
  17. @property(nonatomic,retain)IBOutletUITextField*field3;
  18. @property(nonatomic,retain)IBOutletUITextField*field4;
  19. @end

  1. //
  2. //PersistenceViewController.m
  3. //Persistence4
  4. //
  5. //Createdbyliulavyon11-10-3.
  6. //Copyright2011__MyCompanyName__.Allrightsreserved.
  7. //
  8. #import"PersistenceViewController.h"
  9. #import"Persistence4AppDelegate.h"
  10. @implementationPersistenceViewController
  11. @synthesizefield1;
  12. @synthesizefield2;
  13. @synthesizefield3;
  14. @synthesizefield4;
  15. -(void)applicationWillResignActive:(NSNotification*)notification{
  16. Persistence4AppDelegate*appDelegate=[[UIApplicationsharedApplication]delegate];
  17. NSManagedObjectContext*context=[appDelegatemanagedObjectContext];
  18. NSError*error;
  19. for(inti=1;i<=4;i++){
  20. NSString*fieldName=[NSStringstringWithFormat:@"field%d",i];
  21. UITextField*theField=[selfvalueForKey:fieldName];
  22. //创建提取请求
  23. NSFetchRequest*request=[[NSFetchRequestalloc]init];
  24. //创建实体描述并关联到请求
  25. NSEntityDescription*entityDescription=[NSEntityDescriptionentityForName:@"Line"
  26. inManagedObjectContext:context];
  27. [requestsetEntity:entityDescription];
  28. //设置检索数据的条件
  29. NSPredicate*pred=[NSPredicatepredicateWithFormat:@"(lineNum=%d)",i];
  30. [requestsetPredicate:pred];
  31. NSManagedObject*theLine=nil;
  32. ////检查是否返回了标准匹配的对象,如果有则加载它,如果没有则创建一个新的托管对象来保存此字段的文本
  33. NSArray*objects=[contextexecuteFetchRequest:requesterror:&error];
  34. if(!objects){
  35. NSLog(@"Therewasanerror");
  36. }
  37. //if(objects.count>0){
  38. //theLine=[objectsobjectAtIndex:0];
  39. //}else{
  40. //创建一个新的托管对象来保存此字段的文本
  41. theLine=[NSEntityDescriptioninsertNewObjectForEntityForName:@"Line"
  42. inManagedObjectContext:context];
  43. [theLinesetValue:[NSNumbernumberWithInt:i]forKey:@"lineNum"];
  44. [theLinesetValue:theField.textforKey:@"lineText"];
  45. //}
  46. [requestrelease];
  47. }
  48. //通知上下文保存更改
  49. [contextsave:&error];
  50. }
  51. //Thedesignatedinitializer.OverrideifyoucreatethecontrollerprogrammaticallyandwanttoperformcustomizationthatisnotappropriateforviewDidLoad.
  52. /*
  53. -(id)initWithNibName:(NSString*)nibNameOrNilbundle:(NSBundle*)nibBundleOrNil{
  54. self=[superinitWithNibName:nibNameOrNilbundle:nibBundleOrNil];
  55. if(self){
  56. //Custominitialization.
  57. }
  58. returnself;
  59. }
  60. */
  61. //ImplementviewDidLoadtodoadditionalsetupafterloadingtheview,typicallyfromanib.
  62. -(void)viewDidLoad{
  63. Persistence4AppDelegate*appDelegate=[[UIApplicationsharedApplication]delegate];
  64. NSManagedObjectContext*context=[appDelegatemanagedObjectContext];
  65. //创建一个实体描述
  66. NSEntityDescription*entityDescription=[NSEntityDescriptionentityForName:@"Line"inManagedObjectContext:context];
  67. //创建一个请求,用于提取对象
  68. NSFetchRequest*request=[[NSFetchRequestalloc]init];
  69. [requestsetEntity:entityDescription];
  70. //检索对象
  71. NSError*error;
  72. NSArray*objects=[contextexecuteFetchRequest:requesterror:&error];
  73. if(!objects){
  74. NSLog(@"Therewasanerror!");
  75. }
  76. for(NSManagedObject*objinobjects){
  77. NSNumber*lineNum=[objvalueForKey:@"lineNum"];
  78. NSString*lineText=[objvalueForKey:@"lineText"];
  79. NSString*fieldName=[NSStringstringWithFormat:@"field%d",[lineNumintegerValue]];
  80. UITextField*textField=[selfvalueForKey:fieldName];
  81. textField.text=lineText;
  82. }
  83. [requestrelease];
  84. UIApplication*app=[UIApplicationsharedApplication];
  85. [[NSNotificationCenterdefaultCenter]addObserver:self
  86. selector:@selector(applicationWillResignActive:)
  87. name:UIApplicationWillResignActiveNotification
  88. object:app];
  89. [superviewDidLoad];
  90. }
  91. /*
  92. //Overridetoalloworientationsotherthanthedefaultportraitorientation.
  93. -(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
  94. //ReturnYESforsupportedorientations.
  95. return(interfaceOrientation==UIInterfaceOrientationPortrait);
  96. }
  97. */
  98. -(void)didReceiveMemoryWarning{
  99. //Releasestheviewifitdoesn'thaveasuperview.
  100. [superdidReceiveMemoryWarning];
  101. //Releaseanycacheddata,images,etc.thataren'tinuse.
  102. }
  103. -(void)viewDidUnload{
  104. self.field1=nil;
  105. self.field2=nil;
  106. self.field3=nil;
  107. self.field4=nil;
  108. [superviewDidUnload];
  109. }
  110. -(void)dealloc{
  111. [field1release];
  112. [field2release];
  113. [field3release];
  114. [field4release];
  115. [superdealloc];
  116. }
  117. @end

5、AppSettings

  1. NSUserDefaults*defaults=[NSUserDefaultsstandardUserDefaults];

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

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

6、普通文件存储

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


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

from:http://blog.csdn.net/liuhongwei123888/article/details/6841338

属性列表

对象归档

SQLite3

CoreData

AppSettings

普通文件存储

1、属性列表

  1. //
  2. //Persistence1ViewController.h
  3. //Persistence1
  4. //
  5. //Createdbyliulavyon11-10-3.
  6. //Copyright2011__MyCompanyName__.Allrightsreserved.
  7. //
  8. #import<UIKit/UIKit.h>
  9. #definekFilename@"data.plist"
  10. @interfacePersistence1ViewController:UIViewController{
  11. UITextField*filed1;
  12. UITextField*field2;
  13. UITextField*field3;
  14. UITextField*field4;
  15. }
  16. @property(nonatomic,retain)IBOutletUITextField*field1;
  17. @property(nonatomic,retain)IBOutletUITextField*field2;
  18. @property(nonatomic,retain)IBOutletUITextField*field3;
  19. @property(nonatomic,retain)IBOutletUITextField*field4;
  20. -(NSString*)dataFilePath;
  21. -(void)applicationWillResignActive:(NSNotification*)notification;
  22. @end

  1. //
  2. //Persistence1ViewController.m
  3. //Persistence1
  4. //
  5. //Createdbyliulavyon11-10-3.
  6. //Copyright2011__MyCompanyName__.Allrightsreserved.
  7. //
  8. #import"Persistence1ViewController.h"
  9. @implementationPersistence1ViewController
  10. @synthesizefield1;
  11. @synthesizefield2;
  12. @synthesizefield3;
  13. @synthesizefield4;
  14. //数据文件的完整路径
  15. -(NSString*)dataFilePath{
  16. //检索Documents目录路径。第二个参数表示将搜索限制在我们的应用程序沙盒中
  17. NSArray*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
  18. //每个应用程序只有一个Documents目录
  19. NSString*documentsDirectory=[pathsobjectAtIndex:0];
  20. //创建文件名
  21. return[documentsDirectorystringByAppendingPathComponent:kFilename];
  22. }
  23. //应用程序退出时,将数据保存到属性列表文件
  24. -(void)applicationWillResignActive:(NSNotification*)notification{
  25. NSMutableArray*array=[[NSMutableArrayalloc]init];
  26. [arrayaddObject:field1.text];
  27. [arrayaddObject:field2.text];
  28. [arrayaddObject:field3.text];
  29. [arrayaddObject:field4.text];
  30. [arraywriteToFile:[selfdataFilePath]atomically:YES];
  31. [arrayrelease];
  32. }
  33. /*
  34. //Thedesignatedinitializer.Overridetoperformsetupthatisrequiredbeforetheviewisloaded.
  35. -(id)initWithNibName:(NSString*)nibNameOrNilbundle:(NSBundle*)nibBundleOrNil{
  36. self=[superinitWithNibName:nibNameOrNilbundle:nibBundleOrNil];
  37. if(self){
  38. //Custominitialization
  39. }
  40. returnself;
  41. }
  42. */
  43. /*
  44. //ImplementloadViewtocreateaviewhierarchyprogrammatically,withoutusinganib.
  45. -(void)loadView{
  46. }
  47. */
  48. //ImplementviewDidLoadtodoadditionalsetupafterloadingtheview,typicallyfromanib.
  49. -(void)viewDidLoad{
  50. [superviewDidLoad];
  51. NSString*filePath=[selfdataFilePath];
  52. //检查数据文件是否存在
  53. if([[NSFileManagerdefaultManager]fileExistsAtPath:filePath]){
  54. NSArray*array=[[NSArrayalloc]initWithContentsOfFile:filePath];
  55. field1.text=[arrayobjectAtIndex:0];
  56. field2.text=[arrayobjectAtIndex:1];
  57. field3.text=[arrayobjectAtIndex:2];
  58. field4.text=[arrayobjectAtIndex:3];
  59. [arrayrelease];
  60. }
  61. UIApplication*app=[UIApplicationsharedApplication];
  62. [[NSNotificationCenterdefaultCenter]addObserver:self
  63. selector:@selector(applicationWillResignActive:)
  64. name:UIApplicationWillResignActiveNotification
  65. object:app];
  66. [superviewDidLoad];
  67. }
  68. /*
  69. //Overridetoalloworientationsotherthanthedefaultportraitorientation.
  70. -(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
  71. //ReturnYESforsupportedorientations
  72. return(interfaceOrientation==UIInterfaceOrientationPortrait);
  73. }
  74. */
  75. -(void)didReceiveMemoryWarning{
  76. //Releasestheviewifitdoesn'thaveasuperview.
  77. [superdidReceiveMemoryWarning];
  78. //Releaseanycacheddata,images,etcthataren'tinuse.
  79. }
  80. -(void)viewDidUnload{
  81. self.field1=nil;
  82. self.field2=nil;
  83. self.field3=nil;
  84. self.field4=nil;
  85. [superviewDidUnload];
  86. }
  87. -(void)dealloc{
  88. [field1release];
  89. [field2release];
  90. [field3release];
  91. [field4release];
  92. [superdealloc];
  93. }
  94. @end

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

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

2、对象归档

  1. //
  2. //Fourlines.h
  3. //Persistence2
  4. //
  5. //Createdbyliulavyon11-10-3.
  6. //Copyright2011__MyCompanyName__.Allrightsreserved.
  7. //
  8. #import<Foundation/Foundation.h>
  9. @interfaceFourlines: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. //Createdbyliulavyon11-10-3.
  6. //Copyright2011__MyCompanyName__.Allrightsreserved.
  7. //
  8. #import"Fourlines.h"
  9. #definekField1Key@"Field1"
  10. #definekField2Key@"Field2"
  11. #definekField3Key@"Field3"
  12. #definekField4Key@"Field4"
  13. @implementationFourlines
  14. @synthesizefield1;
  15. @synthesizefield2;
  16. @synthesizefield3;
  17. @synthesizefield4;
  18. #pragmamarkNSCoding
  19. -(void)encodeWithCoder:(NSCoder*)aCoder{
  20. [aCoderencodeObject:field1forKey:kField1Key];
  21. [aCoderencodeObject:field2forKey:kField2Key];
  22. [aCoderencodeObject:field3forKey:kField3Key];
  23. [aCoderencodeObject:field4forKey:kField4Key];
  24. }
  25. -(id)initWithCoder:(NSCoder*)aDecoder{
  26. if(self=[superinit]){
  27. field1=[[aDecoderdecodeObjectForKey:kField1Key]retain];
  28. field2=[[aDecoderdecodeObjectForKey:kField2Key]retain];
  29. field3=[[aDecoderdecodeObjectForKey:kField3Key]retain];
  30. field4=[[aDecoderdecodeObjectForKey:kField4Key]retain];
  31. }
  32. returnself;
  33. }
  34. #pragmamark-
  35. #pragmamarkNSCopying
  36. -(id)copyWithZone:(NSZone*)zone{
  37. Fourlines*copy=[[[selfclass]allocWithZone:zone]init];
  38. copy.field1=[[self.field1copyWithZone:zone]autorelease];
  39. copy.field2=[[self.field2copyWithZone:zone]autorelease];
  40. copy.field3=[[self.field3copyWithZone:zone]autorelease];
  41. copy.field4=[[self.field4copyWithZone:zone]autorelease];
  42. returncopy;
  43. }
  44. @end

  1. //
  2. //Persistence2ViewController.h
  3. //Persistence2
  4. //
  5. //Createdbyliulavyon11-10-3.
  6. //Copyright2011__MyCompanyName__.Allrightsreserved.
  7. //
  8. #import<UIKit/UIKit.h>
  9. #definekFilename@"archive"
  10. #definekDataKey@"Data"
  11. @interfacePersistence2ViewController:UIViewController{
  12. UITextField*filed1;
  13. UITextField*field2;
  14. UITextField*field3;
  15. UITextField*field4;
  16. }
  17. @property(nonatomic,retain)IBOutletUITextField*field1;
  18. @property(nonatomic,retain)IBOutletUITextField*field2;
  19. @property(nonatomic,retain)IBOutletUITextField*field3;
  20. @property(nonatomic,retain)IBOutletUITextField*field4;
  21. -(NSString*)dataFilePath;
  22. -(void)applicationWillResignActive:(NSNotification*)notification;
  23. @end

  1. //
  2. //Persistence2ViewController.m
  3. //Persistence2
  4. //
  5. //Createdbyliulavyon11-10-3.
  6. //Copyright2011__MyCompanyName__.Allrightsreserved.
  7. //
  8. #import"Persistence2ViewController.h"
  9. #import"Fourlines.h"
  10. @implementationPersistence2ViewController
  11. @synthesizefield1;
  12. @synthesizefield2;
  13. @synthesizefield3;
  14. @synthesizefield4;
  15. //数据文件的完整路径
  16. -(NSString*)dataFilePath{
  17. //检索Documents目录路径。第二个参数表示将搜索限制在我们的应用程序沙盒中
  18. NSArray*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
  19. //每个应用程序只有一个Documents目录
  20. NSString*documentsDirectory=[pathsobjectAtIndex:0];
  21. //创建文件名
  22. return[documentsDirectorystringByAppendingPathComponent:kFilename];
  23. }
  24. //应用程序退出时,将数据保存到属性列表文件
  25. -(void)applicationWillResignActive:(NSNotification*)notification{
  26. Fourlines*fourlines=[[Fourlinesalloc]init];
  27. fourlines.field1=field1.text;
  28. fourlines.field2=field2.text;
  29. fourlines.field3=field3.text;
  30. fourlines.field4=field4.text;
  31. NSMutableData*data=[[NSMutableDataalloc]init];//用于存储编码的数据
  32. NSKeyedArchiver*archiver=[[NSKeyedArchiveralloc]initForWritingWithMutableData:data];
  33. [archiverencodeObject:fourlinesforKey:kDataKey];
  34. [archiverfinishEncoding];
  35. [datawriteToFile:[selfdataFilePath]atomically:YES];
  36. [fourlinesrelease];
  37. [archiverrelease];
  38. [datarelease];
  39. }
  40. /*
  41. //Thedesignatedinitializer.Overridetoperformsetupthatisrequiredbeforetheviewisloaded.
  42. -(id)initWithNibName:(NSString*)nibNameOrNilbundle:(NSBundle*)nibBundleOrNil{
  43. self=[superinitWithNibName:nibNameOrNilbundle:nibBundleOrNil];
  44. if(self){
  45. //Custominitialization
  46. }
  47. returnself;
  48. }
  49. */
  50. /*
  51. //ImplementloadViewtocreateaviewhierarchyprogrammatically,withoutusinganib.
  52. -(void)loadView{
  53. }
  54. */
  55. //ImplementviewDidLoadtodoadditionalsetupafterloadingtheview,typicallyfromanib.
  56. -(void)viewDidLoad{
  57. [superviewDidLoad];
  58. NSString*filePath=[selfdataFilePath];
  59. //检查数据文件是否存在
  60. if([[NSFileManagerdefaultManager]fileExistsAtPath:filePath]){
  61. //从文件获取用于解码的数据
  62. NSData*data=[[NSMutableDataalloc]initWithContentsOfFile:[selfdataFilePath]];
  63. NSKeyedUnarchiver*unarchiver=[[NSKeyedUnarchiveralloc]initForReadingWithData:data];
  64. Fourlines*fourlines=[unarchiverdecodeObjectForKey:kDataKey];
  65. [unarchiverfinishDecoding];
  66. field1.text=fourlines.field1;
  67. field2.text=fourlines.field2;
  68. field3.text=fourlines.field3;
  69. field4.text=fourlines.field4;
  70. [unarchiverrelease];
  71. [datarelease];
  72. }
  73. UIApplication*app=[UIApplicationsharedApplication];
  74. [[NSNotificationCenterdefaultCenter]addObserver:self
  75. selector:@selector(applicationWillResignActive:)
  76. name:UIApplicationWillResignActiveNotification
  77. object:app];
  78. [superviewDidLoad];
  79. }
  80. /*
  81. //Overridetoalloworientationsotherthanthedefaultportraitorientation.
  82. -(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
  83. //ReturnYESforsupportedorientations
  84. return(interfaceOrientation==UIInterfaceOrientationPortrait);
  85. }
  86. */
  87. -(void)didReceiveMemoryWarning{
  88. //Releasestheviewifitdoesn'thaveasuperview.
  89. [superdidReceiveMemoryWarning];
  90. //Releaseanycacheddata,images,etcthataren'tinuse.
  91. }
  92. -(void)viewDidUnload{
  93. self.field1=nil;
  94. self.field2=nil;
  95. self.field3=nil;
  96. self.field4=nil;
  97. [superviewDidUnload];
  98. }
  99. -(void)dealloc{
  100. [field1release];
  101. [field2release];
  102. [field3release];
  103. [field4release];
  104. [superdealloc];
  105. }
  106. @end


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

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


3、SQLite

  1. //
  2. //Persistence3ViewController.h
  3. //Persistence3
  4. //
  5. //Createdbyliulavyon11-10-3.
  6. //Copyright2011__MyCompanyName__.Allrightsreserved.
  7. //
  8. #import<UIKit/UIKit.h>
  9. #definekFilename@"data.sqlite3"
  10. @interfacePersistence3ViewController:UIViewController{
  11. UITextField*filed1;
  12. UITextField*field2;
  13. UITextField*field3;
  14. UITextField*field4;
  15. }
  16. @property(nonatomic,retain)IBOutletUITextField*field1;
  17. @property(nonatomic,retain)IBOutletUITextField*field2;
  18. @property(nonatomic,retain)IBOutletUITextField*field3;
  19. @property(nonatomic,retain)IBOutletUITextField*field4;
  20. -(NSString*)dataFilePath;
  21. -(void)applicationWillResignActive:(NSNotification*)notification;
  22. @end

  1. //
  2. //Persistence3ViewController.m
  3. //Persistence3
  4. //
  5. //Createdbyliulavyon11-10-3.
  6. //Copyright2011__MyCompanyName__.Allrightsreserved.
  7. //
  8. #import"Persistence3ViewController.h"
  9. #import<sqlite3.h>
  10. @implementationPersistence3ViewController
  11. @synthesizefield1;
  12. @synthesizefield2;
  13. @synthesizefield3;
  14. @synthesizefield4;
  15. //数据文件的完整路径
  16. -(NSString*)dataFilePath{
  17. //检索Documents目录路径。第二个参数表示将搜索限制在我们的应用程序沙盒中
  18. NSArray*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
  19. //每个应用程序只有一个Documents目录
  20. NSString*documentsDirectory=[pathsobjectAtIndex:0];
  21. //创建文件名
  22. return[documentsDirectorystringByAppendingPathComponent:kFilename];
  23. }
  24. //应用程序退出时,将数据保存到属性列表文件
  25. -(void)applicationWillResignActive:(NSNotification*)notification{
  26. sqlite3*database;
  27. if(sqlite3_open([[selfdataFilePath]UTF8String],&database)!=SQLITE_OK){
  28. sqlite3_close(database);
  29. NSAssert(0,@"Failedtoopendatabase");
  30. }
  31. for(inti=1;i<=4;i++){
  32. NSString*fieldname=[[NSStringalloc]initWithFormat:@"field%d",i];
  33. UITextField*field=[selfvalueForKey:fieldname];
  34. [fieldnamerelease];
  35. char*update="INSERTORREPLACEINTOFIELDS(ROW,FIELD_DATA)VALUES(?,?);";
  36. sqlite3_stmt*stmt;
  37. //将SQL语句编译为sqlite内部一个结构体(sqlite3_stmt),类似javaJDBC的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.textUTF8String],-1,NULL);
  42. }else{
  43. NSAssert(0,@"Error:Failedtopreparestatemen");
  44. }
  45. //执行SQL文,获取结果
  46. intresult=sqlite3_step(stmt);
  47. if(result!=SQLITE_DONE){
  48. NSAssert1(0,@"Errorupdatingtable:%d",result);
  49. }
  50. //释放stmt占用的内存(sqlite3_prepare_v2()分配的)
  51. sqlite3_finalize(stmt);
  52. }
  53. sqlite3_close(database);
  54. }
  55. /*
  56. //Thedesignatedinitializer.Overridetoperformsetupthatisrequiredbeforetheviewisloaded.
  57. -(id)initWithNibName:(NSString*)nibNameOrNilbundle:(NSBundle*)nibBundleOrNil{
  58. self=[superinitWithNibName:nibNameOrNilbundle:nibBundleOrNil];
  59. if(self){
  60. //Custominitialization
  61. }
  62. returnself;
  63. }
  64. */
  65. /*
  66. //ImplementloadViewtocreateaviewhierarchyprogrammatically,withoutusinganib.
  67. -(void)loadView{
  68. }
  69. */
  70. //ImplementviewDidLoadtodoadditionalsetupafterloadingtheview,typicallyfromanib.
  71. -(void)viewDidLoad{
  72. [superviewDidLoad];
  73. NSString*filePath=[selfdataFilePath];
  74. //检查数据文件是否存在
  75. if([[NSFileManagerdefaultManager]fileExistsAtPath:filePath]){
  76. //打开数据库
  77. sqlite3*database;
  78. if(sqlite3_open([filePathUTF8String],&database)!=SQLITE_OK){
  79. sqlite3_close(database);
  80. NSAssert(0,@"Failedtoopendatabase");
  81. }
  82. //创建表
  83. char*errorMsg;
  84. NSString*createSQL=
  85. @"CREATETABLEIFNOTEXISTSFIELDS(ROWINTEGERPRIMARYKEY,FIELD_DATATEXT);";
  86. if(sqlite3_exec(database,[createSQLUTF8String],NULL,NULL,&errorMsg)!=SQLITE_OK){
  87. sqlite3_close(database);
  88. NSAssert(0,@"Errorcreatingtable:%s",errorMsg);
  89. }
  90. //查询
  91. NSString*query=@"SELECTROW,FIELD_DATAFROMFIELDSORDERBYROW";
  92. sqlite3_stmt*statement;
  93. //设置nByte可以加速操作
  94. if(sqlite3_prepare_v2(database,[queryUTF8String],-1,&statement,nil)==SQLITE_OK){
  95. while(sqlite3_step(statement)==SQLITE_ROW){//返回每一行
  96. introw=sqlite3_column_int(statement,0);
  97. char*rowData=(char*)sqlite3_column_text(statement,1);
  98. NSString*fieldName=[[NSStringalloc]initWithFormat:@"field%d",row];
  99. NSString*fieldValue=[[NSStringalloc]initWithUTF8String:rowData];
  100. UITextField*field=[selfvalueForKey:fieldName];
  101. field.text=fieldValue;
  102. [fieldNamerelease];
  103. [fieldValuerelease];
  104. }
  105. //释放statement占用的内存(sqlite3_prepare()分配的)
  106. sqlite3_finalize(statement);
  107. }
  108. sqlite3_close(database);
  109. }
  110. UIApplication*app=[UIApplicationsharedApplication];
  111. [[NSNotificationCenterdefaultCenter]addObserver:self
  112. selector:@selector(applicationWillResignActive:)
  113. name:UIApplicationWillResignActiveNotification
  114. object:app];
  115. [superviewDidLoad];
  116. }
  117. /*
  118. //Overridetoalloworientationsotherthanthedefaultportraitorientation.
  119. -(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
  120. //ReturnYESforsupportedorientations
  121. return(interfaceOrientation==UIInterfaceOrientationPortrait);
  122. }
  123. */
  124. -(void)didReceiveMemoryWarning{
  125. //Releasestheviewifitdoesn'thaveasuperview.
  126. [superdidReceiveMemoryWarning];
  127. //Releaseanycacheddata,images,etcthataren'tinuse.
  128. }
  129. -(void)viewDidUnload{
  130. self.field1=nil;
  131. self.field2=nil;
  132. self.field3=nil;
  133. self.field4=nil;
  134. [superviewDidUnload];
  135. }
  136. -(void)dealloc{
  137. [field1release];
  138. [field2release];
  139. [field3release];
  140. [field4release];
  141. [superdealloc];
  142. }
  143. @end

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

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

4、Core Data

  1. //
  2. //PersistenceViewController.h
  3. //Persistence4
  4. //
  5. //Createdbyliulavyon11-10-3.
  6. //Copyright2011__MyCompanyName__.Allrightsreserved.
  7. //
  8. #import<UIKit/UIKit.h>
  9. @interfacePersistenceViewController:UIViewController{
  10. UITextField*filed1;
  11. UITextField*field2;
  12. UITextField*field3;
  13. UITextField*field4;
  14. }
  15. @property(nonatomic,retain)IBOutletUITextField*field1;
  16. @property(nonatomic,retain)IBOutletUITextField*field2;
  17. @property(nonatomic,retain)IBOutletUITextField*field3;
  18. @property(nonatomic,retain)IBOutletUITextField*field4;
  19. @end

  1. //
  2. //PersistenceViewController.m
  3. //Persistence4
  4. //
  5. //Createdbyliulavyon11-10-3.
  6. //Copyright2011__MyCompanyName__.Allrightsreserved.
  7. //
  8. #import"PersistenceViewController.h"
  9. #import"Persistence4AppDelegate.h"
  10. @implementationPersistenceViewController
  11. @synthesizefield1;
  12. @synthesizefield2;
  13. @synthesizefield3;
  14. @synthesizefield4;
  15. -(void)applicationWillResignActive:(NSNotification*)notification{
  16. Persistence4AppDelegate*appDelegate=[[UIApplicationsharedApplication]delegate];
  17. NSManagedObjectContext*context=[appDelegatemanagedObjectContext];
  18. NSError*error;
  19. for(inti=1;i<=4;i++){
  20. NSString*fieldName=[NSStringstringWithFormat:@"field%d",i];
  21. UITextField*theField=[selfvalueForKey:fieldName];
  22. //创建提取请求
  23. NSFetchRequest*request=[[NSFetchRequestalloc]init];
  24. //创建实体描述并关联到请求
  25. NSEntityDescription*entityDescription=[NSEntityDescriptionentityForName:@"Line"
  26. inManagedObjectContext:context];
  27. [requestsetEntity:entityDescription];
  28. //设置检索数据的条件
  29. NSPredicate*pred=[NSPredicatepredicateWithFormat:@"(lineNum=%d)",i];
  30. [requestsetPredicate:pred];
  31. NSManagedObject*theLine=nil;
  32. ////检查是否返回了标准匹配的对象,如果有则加载它,如果没有则创建一个新的托管对象来保存此字段的文本
  33. NSArray*objects=[contextexecuteFetchRequest:requesterror:&error];
  34. if(!objects){
  35. NSLog(@"Therewasanerror");
  36. }
  37. //if(objects.count>0){
  38. //theLine=[objectsobjectAtIndex:0];
  39. //}else{
  40. //创建一个新的托管对象来保存此字段的文本
  41. theLine=[NSEntityDescriptioninsertNewObjectForEntityForName:@"Line"
  42. inManagedObjectContext:context];
  43. [theLinesetValue:[NSNumbernumberWithInt:i]forKey:@"lineNum"];
  44. [theLinesetValue:theField.textforKey:@"lineText"];
  45. //}
  46. [requestrelease];
  47. }
  48. //通知上下文保存更改
  49. [contextsave:&error];
  50. }
  51. //Thedesignatedinitializer.OverrideifyoucreatethecontrollerprogrammaticallyandwanttoperformcustomizationthatisnotappropriateforviewDidLoad.
  52. /*
  53. -(id)initWithNibName:(NSString*)nibNameOrNilbundle:(NSBundle*)nibBundleOrNil{
  54. self=[superinitWithNibName:nibNameOrNilbundle:nibBundleOrNil];
  55. if(self){
  56. //Custominitialization.
  57. }
  58. returnself;
  59. }
  60. */
  61. //ImplementviewDidLoadtodoadditionalsetupafterloadingtheview,typicallyfromanib.
  62. -(void)viewDidLoad{
  63. Persistence4AppDelegate*appDelegate=[[UIApplicationsharedApplication]delegate];
  64. NSManagedObjectContext*context=[appDelegatemanagedObjectContext];
  65. //创建一个实体描述
  66. NSEntityDescription*entityDescription=[NSEntityDescriptionentityForName:@"Line"inManagedObjectContext:context];
  67. //创建一个请求,用于提取对象
  68. NSFetchRequest*request=[[NSFetchRequestalloc]init];
  69. [requestsetEntity:entityDescription];
  70. //检索对象
  71. NSError*error;
  72. NSArray*objects=[contextexecuteFetchRequest:requesterror:&error];
  73. if(!objects){
  74. NSLog(@"Therewasanerror!");
  75. }
  76. for(NSManagedObject*objinobjects){
  77. NSNumber*lineNum=[objvalueForKey:@"lineNum"];
  78. NSString*lineText=[objvalueForKey:@"lineText"];
  79. NSString*fieldName=[NSStringstringWithFormat:@"field%d",[lineNumintegerValue]];
  80. UITextField*textField=[selfvalueForKey:fieldName];
  81. textField.text=lineText;
  82. }
  83. [requestrelease];
  84. UIApplication*app=[UIApplicationsharedApplication];
  85. [[NSNotificationCenterdefaultCenter]addObserver:self
  86. selector:@selector(applicationWillResignActive:)
  87. name:UIApplicationWillResignActiveNotification
  88. object:app];
  89. [superviewDidLoad];
  90. }
  91. /*
  92. //Overridetoalloworientationsotherthanthedefaultportraitorientation.
  93. -(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
  94. //ReturnYESforsupportedorientations.
  95. return(interfaceOrientation==UIInterfaceOrientationPortrait);
  96. }
  97. */
  98. -(void)didReceiveMemoryWarning{
  99. //Releasestheviewifitdoesn'thaveasuperview.
  100. [superdidReceiveMemoryWarning];
  101. //Releaseanycacheddata,images,etc.thataren'tinuse.
  102. }
  103. -(void)viewDidUnload{
  104. self.field1=nil;
  105. self.field2=nil;
  106. self.field3=nil;
  107. self.field4=nil;
  108. [superviewDidUnload];
  109. }
  110. -(void)dealloc{
  111. [field1release];
  112. [field2release];
  113. [field3release];
  114. [field4release];
  115. [superdealloc];
  116. }
  117. @end

5、AppSettings

  1. NSUserDefaults*defaults=[NSUserDefaultsstandardUserDefaults];

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

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

6、普通文件存储

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


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

from:http://blog.csdn.net/liuhongwei123888/article/details/6841338
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics