iPhone 数据持久储存的几种方式

1 ,用存文件的方式实现持久存储

2 ,NSUserDefault 简单数据存储

3 ,数据库存取

    //

//  TestBedViewController.m

//  Core_DataTest

//

//  Created by mir on 11-3-31.

//  Copyright 2011 __MyCompanyName__. All rights reserved.

//

#import "TestBedViewController.h"

#import "Department.h"

#import "Person.h"

#define COOKBOOK_PURPLE_COLOR [UIColor colorWithRed:0.20392f green:0.19607f blue:0.61176f alpha:1.0f]

#define BARBUTTON(TITLE, SELECTOR) [[[UIBarButtonItem alloc] initWithTitle:TITLE style:UIBarButtonItemStylePlain target:self action:SELECTOR] autorelease]

#define STOREPATH [NSHomeDirectory() stringByAppendingString:@"/Documents/cdintro_00.sqlite"]

@implementation TestBedViewController

@synthesize context;

@synthesize fetchedResultsController;

/*

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {

    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {

        // Custom initialization

    }

    return self;

}

*/

/*

// Implement loadView to create a view hierarchy programmatically, without using a nib.

- (void)loadView {

}

*/

//初始化数据库信息

-(void) initCoreData{

NSError *error;

//Path to sqlite file.

NSString *path=STOREPATH;//[NSHomeDirectory() stringByAppendingFormat:@"/Documents/cdintro_00_sqlite"];

NSURL *url=[NSURL fileURLWithPath:path];

//Init the model

NSManagedObjectModel *managedObjectModel=[NSManagedObjectModel mergedModelFromBundles:nil];

//Establish the persistent store coordinator 建立持久存储协调员

NSPersistentStoreCoordinator *persistentStoreCoordinator=[[NSPersistentStoreCoordinator alloc] 

 initWithManagedObjectModel:managedObjectModel];

if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType 

 configuration:nil URL:url 

options:nil error:&error]) {

NSLog(@"init Error %@",[error localizedDescription]);

}else{

//Create the context and assign the coordinator

self.context=[[[NSManagedObjectContext alloc] init] autorelease];

[self.context setPersistentStoreCoordinator:persistentStoreCoordinator];//设置协调员

}

[persistentStoreCoordinator release];

}

- (NSDate *) dateFromString: (NSString *) aString

{

// Return a date from a string

NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];

formatter.dateFormat = @"MM-dd-yyyy";

NSDate *date = [formatter dateFromString:aString];

return date;

}

//添加数据对象

-(void) addObjects{

//Add a new department

Department *department=(Department *)[NSEntityDescription insertNewObjectForEntityForName:@"Department" 

  inManagedObjectContext:self.context];

department.groupName=infoField.text==nil?@"office of Personnel management":infoField.text;

//Add a person

Person *person1=(Person *)[NSEntityDescription insertNewObjectForEntityForName:@"Person" 

inManagedObjectContext:self.context];

person1.name=nameField.text==nil?@"John Smith":nameField.text;

person1.birthday=[self dateFromString:@"12-1-1901"];

person1.department=department;

//Add another person

Person *person2=(Person *)[NSEntityDescription insertNewObjectForEntityForName:@"Person" 

inManagedObjectContext:self.context];

person2.name=[NSString stringWithFormat:@"%@Jane Doe",nameField.text==nil?@"":nameField.text];

person2.birthday=[self dateFromString:@"4-13-1922"];

person2.department=department;

//Set the departemnt reltionships

department.manager=person1;

//Save out to the persistent store

NSError *error;

if (![self.context save:&error]) {

NSLog(@"Error %@",[error localizedDescription]);

}

}

//读取数据对象

-(void) fetchObjects{

//Create a basic fetch request

NSFetchRequest *fetchRequest=[[NSFetchRequest alloc] init];

[fetchRequest setEntity:[NSEntityDescription entityForName:@"Person" 

inManagedObjectContext:self.context]];

//Add a sort descriptor. Mandatory.

NSSortDescriptor *sortDescriptor=[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES selector:nil];

NSArray *descriptor=[NSArray arrayWithObject:sortDescriptor];

[fetchRequest setSortDescriptors:descriptor];

[sortDescriptor release];

//Init the fetched results controller

NSError *error;

self.fetchedResultsController=[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest 

 managedObjectContext:self.context 

sectionNameKeyPath:nil cacheName:@"Root"];

if (![self.fetchedResultsController performFetch:&error]) {

NSLog(@"Error %@",[error localizedDescription]);

}

[self.fetchedResultsController release];

[fetchRequest release];

}

//显示数据对象

-(void) action:(UIBarButtonItem *)bbi{

[self fetchObjects];

NSMutableString *info=[[NSMutableString alloc] initWithCapacity:42];

for (Person *person in self.fetchedResultsController.fetchedObjects) {

NSLog(@"%@   :  %@",person.name,person.department.groupName);

[info appendFormat:@"%@   :  %@\n",person.name,person.department.groupName];

}

tview.text=info;

[info release];

}

//删除数据对象

-(void) removeObjects{

NSError *error=nil;

///Remove all people(if they exist)

[self fetchObjects];

if (!self.fetchedResultsController.fetchedObjects.count) {

NSLog(@"No one to delete");

return;

}

//Remove each person

for (Person *person in self.fetchedResultsController.fetchedObjects) {

//NSLog(@"person.department.groupName %@",person.department.groupName);

// NSLog(@" nameField.text %@",nameField.text);

//Remove person as manager if necessary

if (person.department.manager==person) {

person.department.manager=nil;

[self.context deleteObject:person];

}

//如果查询的姓名与部门等于要删除的 就删除

if ([person.name isEqualToString:nameField.text] && [person.department.groupName isEqualToString:infoField.text]) {

[self.context deleteObject:person];

}

}

if (![self.context save:&error]) {

NSLog(@"Error %@ (%@)",[error localizedDescription]);

}

}

//修改数据

-(void) updateObjects{

NSError *error=nil;

[self fetchObjects];

if (!self.fetchedResultsController.fetchedObjects.count) {

NSLog(@"No one to delete");

return;

}

for (Person *person in self.fetchedResultsController.fetchedObjects) {

//如果名字等于输入的那么就修改

/**使用谓词表达式 start*/

NSPredicate *perdicate=[NSPredicate predicateWithFormat:@"name==%@",nameField.text];

BOOL match=[perdicate evaluateWithObject:person];

NSLog(@"%s",(match)?"YES":"NO");

/**使用谓词表达式 end*/

if ([person.name isEqualToString:nameField.text]) {

person.name=infoField.text;

}

[self.context updatedObjects];

}

if (![self.context save:&error]) {

NSLog(@"Error %@ (%@)",[error localizedDescription]);

}

}

//-(void) segmentAction:(UISegmentedControl *)sender{

//

// if ([sender selectedSegmentIndex]==0) {

// NSLog(@"removeObjects");

// [self removeObjects];

// }else if ([sender selectedSegmentIndex]==1) {

// NSLog(@"updateObjects");

// [self updateObjects];

// }

//

//}

-(BOOL) textFieldShouldReturn:(UITextField *)textField{

[textField resignFirstResponder];

return YES;

}

-(void) buttonPreesend:(UIButton *)sender{

[sender backgroundImageForState:UIControlStateSelected];

if (sender.tag==100) {//添加

NSLog(@"添加");

[self addObjects];

}else if (sender.tag==101) {//删除

NSLog(@"删除");

[self removeObjects];

}else if (sender.tag==102) {//修改

NSLog(@"修改");

[self updateObjects];

}else if (sender.tag==103) {//查询

NSLog(@"查询");

[self action:nil];

}

[self action:nil];

}

- (void)initCalc {

//she zhi beijingse 

self.view.backgroundColor=[UIColor cyanColor];

UILabel *firstLable=[[UILabel alloc] initWithFrame:CGRectMake(10, 40, self.view.frame.size.width, 40)];

firstLable.font=[UIFont systemFontOfSize:12.0f];

firstLable.text=[NSString stringWithFormat:@"name:"];

firstLable.backgroundColor=[UIColor clearColor];

[self.view addSubview:firstLable];

[firstLable release];

UILabel *secondLable=[[UILabel alloc]initWithFrame:CGRectMake(10, 80, self.view.frame.size.width, 40)];

secondLable.font=[UIFont systemFontOfSize:12.0f];

secondLable.text=[NSString stringWithFormat:@"groupName:"];

secondLable.backgroundColor=[UIColor clearColor];

[self.view addSubview:secondLable];

[secondLable release];

nameField=[[UITextField alloc]initWithFrame:CGRectMake(100, 50, 150, 30)];

nameField.backgroundColor=[UIColor clearColor];

nameField.borderStyle=UITextBorderStyleRoundedRect;

nameField.autocorrectionType=UITextAutocorrectionTypeNo;

nameField.returnKeyType=UIReturnKeyDone;

nameField.delegate=self;

[self.view addSubview:nameField];

[nameField release];

infoField=[[UITextField alloc]initWithFrame:CGRectMake(100, 90, 150, 30)];

infoField.backgroundColor=[UIColor clearColor];

infoField.borderStyle=UITextBorderStyleRoundedRect;

infoField.autocorrectionType=UITextAutocorrectionTypeNo;

infoField.delegate=self;

[self.view addSubview:infoField];

[infoField release];

NSString *calcStr[]={@"添加",@"删除",@"修改",@"查询"};

int avg_w=self.view.frame.size.width/4;//平均框度

int first_x=(avg_w-60)/2;

for (int i=0; i<4; i++) {

//创建圆角矩形按钮

UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect]; 

[button setTag:100+i];

[button setFrame:CGRectMake(first_x+i*(first_x+60), 140, 60, 28)];

[button setTitle:calcStr[i] forState:UIControlStateNormal];

[button addTarget:self action:@selector(buttonPreesend:) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:button];

}

}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.

- (void)viewDidLoad {

    [super viewDidLoad];

self.navigationItem.title=@"保存持久数据测试";

//self.navigationController.navigationBar.tintColor=[UIColor clearColor];

//self.navigationController.navigationBar.alpha=0.5f;

//self.navigationItem.rightBarButtonItem=BARBUTTON(@"Add",@selector(addObjects));

// self.navigationItem.leftBarButtonItem=BARBUTTON(@"action",@selector(action:));

//

// //Create the segmented control

// NSArray *buttonNames=[NSArray arrayWithObjects:@"Remove",@"Update",nil];

// UISegmentedControl* segmentedControl=[[UISegmentedControl alloc] initWithItems:buttonNames];

// segmentedControl.segmentedControlStyle=UISegmentedControlStyleBar;

// segmentedControl.momentary=YES;

// [segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventAllEvents];

// self.navigationItem.titleView=segmentedControl;

// [segmentedControl release];

[self initCoreData];//初始化数据库信息

[self initCalc];//初始化操作信息

//显示数据信息

tview=[[UITextView alloc] initWithFrame:CGRectMake(10, 190, 300, self.view.frame.size.height-220)];

[tview setEditable:NO];

[tview setDataDetectorTypes:UIDataDetectorTypeAll];

[self.view addSubview:tview];

[tview release];

}

// Override to allow orientations other than the default portrait orientation.

//- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {

//    // Return YES for supported orientations

//   // return (interfaceOrientation == UIInterfaceOrientationPortrait);

// return YES;

//}

- (void)didReceiveMemoryWarning {

    // Releases the view if it doesn't have a superview.

    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.

}

- (void)viewDidUnload {

    [super viewDidUnload];

    // Release any retained subviews of the main view.

    // e.g. self.myOutlet = nil;

}

- (void)dealloc {

    [super dealloc];

}

@end


猜你喜欢

转载自374016526.iteye.com/blog/1156908