本文主要是介绍ios coreData sqlite3,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
//
// ViewController.m
// CoreDataByStoryboard
//
// Created by 何瑾 on 15/1/15.
// Copyright (c) 2015年 e世雕龙. All rights reserved.
//#import "ViewController.h"
#import "Student.h"@interface ViewController ()@property (weak, nonatomic) IBOutlet UITextField *txtName;// 姓名文本框
@property (weak, nonatomic) IBOutlet UITextField *txtAge;// 年龄文本框
@property (weak, nonatomic) IBOutlet UITextField *txtID;// ID文本框
@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;// 托管对象上下文(类似于sqlite3编程中数据库的缓冲区)
@property (strong, nonatomic) NSArray *students;// 查询出来的学生数组
@end@implementation ViewController- (void)viewDidLoad {[super viewDidLoad];[self getDocPath];// Do any additional setup after loading the view, typically from a nib.// 1、获取应用程序对象UIApplication *app = [UIApplication sharedApplication];// 2、获取应用程序的委托id appDelegate = app.delegate;// 3、获取应用程序中的托管对象上下文self.managedObjectContext = [appDelegate managedObjectContext];
}
#pragma mark 注册
- (IBAction)btnRegister:(id)sender {// 通过实体描述类创建数据模型(托管对象)放入托管对象上下文中Student *stu = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:self.managedObjectContext];// 给数据模型(托管对象)属性绑定界面数据static int i = 0;i++;stu.id = [NSNumber numberWithInt:i];stu.name = self.txtName.text;stu.age = [NSNumber numberWithInt:[self.txtAge.text intValue]];stu.address = @"北京人";// 通过托管对象上下文保存数据模型(托管对象)__autoreleasing NSError *error = nil;[self.managedObjectContext save:&error];// 判断是否保存成功if (error) {[self myAlert:@"托管对象保存失败!"];} else {[self myAlert:@"托管对象保存成功!"];}
}
#pragma mark 查询
- (IBAction)btnSearch:(id)sender {// 1、创建抓取请求对象NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Student"];// 从界面获取查询条件NSNumber *id = [NSNumber numberWithInt:[self.txtID.text intValue]];NSLog(@"id:%@",id);// 2、创建谓词(查询条件)NSPredicate *predicate = [NSPredicate predicateWithFormat:@"id=%@",id];// 2.1把谓词放入抓取请求对象中[request setPredicate:predicate];// 3、创建排序规则NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]initWithKey:@"id" ascending:YES];// 3.1把排序规则放入抓取请求对象中[request setSortDescriptors:@[sortDescriptor]];// 4、执行抓取(查询)__autoreleasing NSError *error = nil;self.students = [self.managedObjectContext executeFetchRequest:request error:&error];if (error) {[self myAlert:@"查询失败!"];} else {[self myAlert:@"查询成功!请看控制台!"];NSLog(@"students:%@",self.students);}
}
#pragma mark 封装UIAlertView
- (void)myAlert:(NSString *)errorMsg {UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"信息" message:errorMsg delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];[alert show];
}
#pragma mark 获取应用沙盒的documents目录路径
- (NSString *)getDocPath {NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);NSString *docPath = docPaths[0];NSLog(@"docPath:%@",docPath);return docPath;
}
@end
这篇关于ios coreData sqlite3的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!