zoukankan      html  css  js  c++  java
  • IOS 数据储存

    IOS 数据存储

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

    属性列表

    对象归档

    SQLite3

    CoreData

    AppSettings

    普通文件存储

    1、属性列表

    [cpp] view plaincopy
     
     
    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 plaincopy
     
     
    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. // Implement loadView to create a view hierarchy programmatically, without using a nib. 
    50. - (void)loadView { 
    51. */  
    52.   
    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.         NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];  
    62.         field1.text = [array objectAtIndex:0];  
    63.         field2.text = [array objectAtIndex:1];  
    64.         field3.text = [array objectAtIndex:2];  
    65.         field4.text = [array objectAtIndex:3];  
    66.         [array release];  
    67.     }  
    68.     UIApplication *app = [UIApplication sharedApplication];  
    69.     [[NSNotificationCenter defaultCenter] addObserver:self  
    70.                                             selector:@selector(applicationWillResignActive:)  
    71.                                             name:UIApplicationWillResignActiveNotification  
    72.                                             object:app];  
    73.     [super viewDidLoad];  
    74. }  
    75.   
    76.   
    77. /* 
    78. // Override to allow orientations other than the default portrait orientation. 
    79. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { 
    80.     // Return YES for supported orientations 
    81.     return (interfaceOrientation == UIInterfaceOrientationPortrait); 
    82. */  
    83.   
    84. - (void)didReceiveMemoryWarning {  
    85.     // Releases the view if it doesn't have a superview.  
    86.     [super didReceiveMemoryWarning];  
    87.       
    88.     // Release any cached data, images, etc that aren't in use.  
    89. }  
    90.   
    91. - (void)viewDidUnload {  
    92.     self.field1 = nil;  
    93.     self.field2 = nil;  
    94.     self.field3 = nil;  
    95.     self.field4 = nil;  
    96.     [super viewDidUnload];  
    97. }  
    98.   
    99.   
    100. - (void)dealloc {  
    101.     [field1 release];  
    102.     [field2 release];  
    103.     [field3 release];  
    104.     [field4 release];  
    105.     [super dealloc];  
    106. }  
    107.   
    108. @end  

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

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

    2、对象归档
    [cpp] view plaincopy
     
     
    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 plaincopy
     
     
    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 plaincopy
     
     
    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 plaincopy
     
     
    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 plaincopy
     
     
    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 plaincopy
     
     
    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 plaincopy
     
     
    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 plaincopy
     
     
    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. // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.  
    72. - (void)viewDidLoad {  
    73.     Persistence4AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];  
    74.       
    75.     NSManagedObjectContext *context = [appDelegate managedObjectContext];  
    76.     //创建一个实体描述  
    77.     NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Line" inManagedObjectContext:context];  
    78.     //创建一个请求,用于提取对象  
    79.     NSFetchRequest *request = [[NSFetchRequest alloc] init];  
    80.     [request setEntity:entityDescription];  
    81.       
    82.     //检索对象  
    83.     NSError *error;  
    84.     NSArray *objects = [context executeFetchRequest:request error:&error];  
    85.     if(!objects) {  
    86.         NSLog(@"There was an error!");  
    87.     }  
    88.     for(NSManagedObject *obj in objects) {  
    89.         NSNumber *lineNum = [obj valueForKey:@"lineNum"];  
    90.         NSString *lineText = [obj valueForKey:@"lineText"];  
    91.         NSString *fieldName = [NSString stringWithFormat:@"field%d", [lineNum integerValue]];  
    92.         UITextField *textField = [self valueForKey:fieldName];  
    93.         textField.text = lineText;  
    94.     }  
    95.     [request release];  
    96.       
    97.     UIApplication *app = [UIApplication sharedApplication];  
    98.     [[NSNotificationCenter defaultCenter] addObserver:self   
    99.                                              selector:@selector(applicationWillResignActive:)   
    100.                                                  name:UIApplicationWillResignActiveNotification  
    101.                                                object:app];  
    102.     [super viewDidLoad];  
    103. }  
    104.   
    105. /* 
    106. // Override to allow orientations other than the default portrait orientation. 
    107. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { 
    108.     // Return YES for supported orientations. 
    109.     return (interfaceOrientation == UIInterfaceOrientationPortrait); 
    110. */  
    111.   
    112. - (void)didReceiveMemoryWarning {  
    113.     // Releases the view if it doesn't have a superview.  
    114.     [super didReceiveMemoryWarning];  
    115.       
    116.     // Release any cached data, images, etc. that aren't in use.  
    117. }  
    118.   
    119. - (void)viewDidUnload {  
    120.     self.field1 = nil;  
    121.     self.field2 = nil;  
    122.     self.field3 = nil;  
    123.     self.field4 = nil;  
    124.     [super viewDidUnload];  
    125. }  
    126.   
    127.   
    128. - (void)dealloc {  
    129.     [field1 release];  
    130.     [field2 release];  
    131.     [field3 release];  
    132.     [field4 release];  
    133.     [super dealloc];  
    134. }  
    135.   
    136.   
    137.   
    138. @end  

    5、AppSettings
    [cpp] view plaincopy
     
     
    1. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];  

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

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

    6、普通文件存储

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

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

  • 相关阅读:
    php json_encode数据格式化2种格式[]和{}
    PHP实现执行定时任务的几种思路详解
    PHP json_encode 转换成空对象和空数组
    程序员职业病的种类和预防
    清空数据表并重置索引
    实现PHP中的 JSON_ENCODE 不转义中文汉字的方法
    pchart生成折线图
    自定义皮肤啦
    honeyview——本地图片浏览器
    使用potplayer视频播放器的录制屏幕功能
  • 原文地址:https://www.cnblogs.com/sinodragon21/p/4819643.html
Copyright © 2011-2022 走看看