`
374016526
  • 浏览: 99256 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

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


分享到:
评论

相关推荐

    iphone view之间传送数据

    首先,我们来看一下几种常用的数据传递方法: 1. **属性赋值**:如果view1和view2之间存在明确的父子关系或者兄弟关系,可以直接通过属性来传递数据。例如,在view2的dismiss或pop方法中,将数据设置给view1的一个...

    iPhone开发实战.pdf

    Core Data是iOS提供的一种对象持久化框架,用于管理应用的数据模型层。它简化了数据存储和检索的过程,使开发者能够更加专注于业务逻辑的实现而非底层的数据操作。 ### 三、实战案例分析 虽然给定的部分内容没有...

    读写数据-数据归档源码

    在iOS应用中,数据读取通常涉及到以下几种方式: 1. **UserDefaults**:适用于存储轻量级的偏好设置或简单数据,如用户设置、开关状态等。UserDefaults提供了一种键值对的存储方式,易于使用,但不适合大量或复杂...

    iPhone 高级项目开发

    - **网络请求库**: 推荐了几种常用的网络请求库(如AFNetworking),并指导如何使用这些库简化网络通信的实现。 ##### 3.6 安全与加密 - **数据加密**: 介绍了如何对敏感数据进行加密处理,确保数据的安全性。 - **...

    iphone版暖靴GO产品

    标题 "iphone版暖靴GO产品" 暗示我们讨论的是一个针对iPhone用户的移动应用程序,可能是一个生活助手类的应用,其特色可能是为用户提供舒适、保暖的鞋靴推荐或相关服务。"暖靴GO"这个名字可能是应用的简称或者品牌名...

    iPhone开发基础教程-PDF完整版 part 1

    Core Data是苹果提供的一套对象持久化框架,它为应用的数据模型提供了一种面向对象的抽象层,简化了数据的存储和检索过程。Core Data支持SQLite数据库,能够处理复杂的数据关系和事务管理。 #### 3.2 **...

    iPhone官方解析XML示例-XMLPerformance

    XML(eXtensible Markup Language)是一种用于标记数据的语言,广泛应用于网络数据交换、配置文件存储等领域。在iOS开发中,处理XML数据是一项常见的任务,尤其是当你需要与服务器进行数据交互时。本示例"iPhone官方...

    iphone新闻资讯系统

    5. **数据持久化**:可能涉及到Core Data或SQLite来存储用户偏好或离线阅读的新闻。 6. **推送通知**:集成Apple Push Notification service(APNs)为用户提供实时的新闻更新提醒。 7. **性能优化**:理解如何减少...

    iphone开发基础教程(源代码)

    iOS提供了几种数据持久化方法,如UserDefaults(用于轻量级数据存储)、Core Data(面向对象的数据模型)和SQLite(关系数据库)。了解这些技术并根据需求选择合适的方法至关重要。 网络通信是许多现代应用的基础。...

    Iphone 序列化与反序列化,队列的实例

    iOS提供了几种不同类型的队列: 1. **主队列(Main Queue)**:运行在主线程上,用于更新UI和处理用户交互。 2. **全局并发队列(Global Dispatch Queues)**:提供多线程能力,处理后台任务,有四个优先级可供选择...

    Objective-C_for_iPhone_Developers.pdf

    5. **数据持久化**:Objective-C 支持多种数据存储方式,包括 Core Data、SQLite 等技术,帮助开发者实现数据的持久化存储。 #### 四、Objective-C 的学习资源 1. **官方文档**:苹果官方提供了详尽的 Objective-C ...

    iPhone SDK Application Development

    6. **Core Data**:苹果的持久化框架,用于存储和检索应用程序的数据。理解实体关系、NSManagedObject、fetch requests和MVC(Model-View-Controller)设计模式对数据管理很有帮助。 7. **动画与Core Animation**:...

    iPhone一个简单程序

    7. **Core Data**: 这是苹果提供的一个持久化框架,用于存储和检索数据。对于简单的应用,可能直接使用SQLite数据库,但对于复杂项目,Core Data提供更强大的数据模型管理。 8. **ARC(Automatic Reference ...

    Beginning iPhone Development with Swift

    本章将介绍几种常用的数据存储方案。 - **第14章:文档与iCloud** - iCloud是苹果提供的一项云服务,支持跨设备同步应用数据。本章将探讨如何利用iCloud实现数据同步。 - **第15章:Grand Central Dispatch、后台...

    iPhone 游戏编程实例 PDF + 源码

    8. **Core Data**:数据持久化框架,用于存储游戏进度、用户数据等,确保数据在应用关闭后仍然保留。 9. **多线程编程**:为了确保游戏流畅运行,理解并合理使用多线程技术来分离计算密集型任务和用户交互是非常...

    3G iPhone 手机开发资料收集

    3. 数据管理:包括Core Data用于持久化存储,以及UserDefaults进行轻量级数据存储。 4. 网络请求:利用URLSession或第三方库如Alamofire进行网络通信。 5. 多线程:理解GCD(Grand Central Dispatch)和操作队列在...

    iPhone应用程序开发指南.pdf.

    Core Data是Apple提供的一种数据管理框架,用于存储和检索应用程序的数据。它提供了一种对象关系映射(ORM)机制,使得开发者可以方便地处理结构化数据,同时支持数据持久化,即使应用程序关闭或设备重启,也能保持...

    iPhone开发进阶

    Objective-C提供了几种常用的容器类来存储对象集合,包括数组、字典和Set。这些容器不直接存储基本类型如int或float,而是通过NSNumber等封装类来存储。 **3.3 Notification** Notification是一种消息通知机制,...

Global site tag (gtag.js) - Google Analytics