// DBManager.h
// DB
//
// Created by qianfeng on 15/7/22.
// Copyright (c) 2015年 张国锋. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "UserModel.h"
@interface DBManager : NSObject
+ (DBManager *)shareManager;
//- (id)init;
- (void)insertModel:(UserModel *)model;
- (void)deleteDataWith:(NSNumber *)dataID;
- (void)updateWith:(UserModel *)model;
- (NSArray *)selectAllData;
- (BOOL)isOrNotIN:(NSNumber *)idOne;
@end
//
// DBManager.m
// DB
//
// Created by qianfeng on 15/7/22.
// Copyright (c) 2015年 张国锋. All rights reserved.
//
#import "DBManager.h"
#import "FMDatabase.h"
@implementation DBManager
{
FMDatabase *_fmdb;
NSLock *_lock;//锁
}
+ (DBManager *)shareManager
{
static DBManager *manager =nil;
static dispatch_once_t once;
dispatch_once(&once, ^{
if (manager==nil) {
manager =[[DBManager alloc]init];
}
});
return manager;
}
- (id)init
{
self =[super init];
if (self) {
_lock =[[NSLock alloc]init];
// [_lock lock];//加锁
//
// [_lock unlock];//解锁
//
NSString *path=[NSHomeDirectory() stringByAppendingString:@"/Documents/user1.db"];
_fmdb=[[FMDatabase alloc]initWithPath:path];
if ([_fmdb open]) {
NSString *createSql=@"create table if not exists userInfo(id integer primary key autoincrement,name varchar(256),age integer,image blob)";//创建一个userInfo表,blob是用来存储2进制的,如图片
BOOL success =[_fmdb executeUpdate:createSql]; //增,删,改都用此方法executeUpdate
if (!success) {
NSLog(@"%@",_fmdb.lastError);
}
}
//[_fmdb close];//关闭数据库连接
}
return self;
}
- (void)insertModel:(UserModel *)model
{
[_lock lock];
NSString *insertSql =@"insert into userInfo(name,age,image) values(?,?,?)";
UIImage *image =model.headImage;
NSData *data =UIImagePNGRepresentation(image);
//这个方法是可以讲png类型的图片转化成NSData
BOOL success=[_fmdb executeUpdate:insertSql,model.name,model.age,data];
//executeUpdate 后面需要去接 继承于NSobject类所实例化对象,否则会抛出EXC_BAD_ACCESS 错误
if (!success) {
NSLog(@"%@",_fmdb.lastError);
}
[_lock unlock];//解锁
//[_fmdb close];
}
//删除一条数据
- (void)deleteDataWith:(NSNumber *)dataID
{
[_lock lock];
NSString *deleteSql =@"delete from userInfo where id=?"; //? 相当于%@
BOOL success =[_fmdb executeUpdate:deleteSql,dataID];
if (!success) {
NSLog(@"%@",_fmdb.lastError);
}
[_lock unlock];//解锁
}
//更新一条数据
- (void)updateWith:(UserModel *)model
{
[_lock lock];
NSString *updateSql =@"update userinfo set name=?,age=?,image=? where id=?";
UIImage *image =model.headImage;
NSData *data =UIImagePNGRepresentation(image);
NSNumber *IDNum =[NSNumber numberWithInteger:[model.id1 integerValue]];
BOOL success =[_fmdb executeUpdate:updateSql,model.name,model.age,data,IDNum];
if (!success) {
NSLog(@"%@",_fmdb.lastError);
}
[_lock unlock];
}
- (NSArray *)selectAllData
{
[_lock lock];
NSString *selSQL =@"select * from userInfo";
FMResultSet *set = [_fmdb executeQuery:selSQL];
NSMutableArray *array =[NSMutableArray array];
while ([set next]) {
UserModel *model =[[UserModel alloc]init];
model.name=[set stringForColumn:@"name"];//
NSData *data=[set dataForColumn:@"image"];
UIImage *image =[UIImage imageWithData:data];//把NSData类型的数据转化成image
model.headImage=image;
model.age= [NSNumber numberWithInteger:[[set stringForColumn:@"age"] integerValue]] ;
[array addObject:model];
}
[_lock unlock];
return [array copy];
}
//查询一条语句是否存在
- (BOOL)isOrNotIN:(NSNumber *)idOne
{
//
// ViewController.m
// DB
//
// Created by qianfeng on 15/7/22.
// Copyright (c) 2015年 张国锋. All rights reserved.
//
#import "ViewController.h"
#import "DetailViewController.h"
#import "DBManager.h"
@interface ViewController () <UITableViewDelegate,UITableViewDataSource,reloadProtocol>
{
UITableView *_tabelView;
NSMutableArray *_dataArray;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self configUI];
[self loadData];
}
- (void)loadData
{
NSArray *array =[[DBManager shareManager] selectAllData];
_dataArray =[array mutableCopy];
[_tabelView reloadData];
}
- (void)configUI
{
self.view.backgroundColor=[UIColor whiteColor];
UIBarButtonItem *bar =[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(push)];
self.navigationItem.rightBarButtonItem=bar;
_tabelView= [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
_tabelView.delegate=self;
_tabelView.dataSource=self;
[_tabelView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
[self.view addSubview:_tabelView];
_dataArray =[NSMutableArray array];
}
- (void)push
{
DetailViewController *vc =[[DetailViewController alloc]init];
// vc.delegate=self;
vc.rdBlock=^{
NSArray *array =[[DBManager shareManager] selectAllData];
_dataArray =[array mutableCopy];
[_tabelView reloadData]; //可能出现强强引用的问题
};
[self.navigationController pushViewController:vc animated:YES];
}
-(void)reloadDataMath
{
NSLog(@"12");
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
UserModel *model =_dataArray[indexPath.row];
cell.imageView.image=model.headImage;
cell.textLabel.text=model.name;
cell.detailTextLabel.text=[NSString stringWithFormat:@"%@",model.age];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 100;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
// DetailViewController.h
// DB
//
// Created by qianfeng on 15/7/22.
// Copyright (c) 2015年 张国锋. All rights reserved.
//
#import <UIKit/UIKit.h>
@protocol reloadProtocol <NSObject>
-(void)reloadDataMath;
@end
typedef void (^rDBlock)();
@interface DetailViewController : UIViewController
@property (nonatomic,strong) rDBlock rdBlock;
@property (nonatomic,assign) id <reloadProtocol>delegate;
@end
//
// DetailViewController.m
// DB
//
// Created by qianfeng on 15/7/22.
// Copyright (c) 2015年 张国锋. All rights reserved.
//
#import "DetailViewController.h"
#import "GFControl.h"
#import "DBManager.h"
#import <MobileCoreServices/MobileCoreServices.h>
@interface DetailViewController () <UIActionSheetDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
{
UITextField *_nameField;
UITextField *_ageField;
UIButton *_headImage;//头像
UIImage *_image;
}
@end
@implementation DetailViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor =[UIColor whiteColor];
[self configUI];
}
- (void)configUI
{
CGFloat width=self.view.frame.size.width;
UILabel *nameLabel =[GFControl createLabelWithFontSize:18 WithFrame:CGRectMake(30, 100, 80, 30) WithText:@"姓名"];
[self.view addSubview:nameLabel];
_nameField=[GFControl createTextFieldWithFrame:CGRectMake(120, 100, width-120-30, 30)];
[self.view addSubview:_nameField];
UILabel *ageLabel=[GFControl createLabelWithFontSize:18 WithFrame:CGRectMake(30, 150, 80, 30) WithText:@"年龄"];
[self.view addSubview:ageLabel];
_ageField=[GFControl createTextFieldWithFrame:CGRectMake(120, 150, width-120-30, 30)];
[self.view addSubview:_ageField];
UILabel *headLabel =[GFControl createLabelWithFontSize:18 WithFrame:CGRectMake(30, 200, 80, 30) WithText:@"头像"];
[self.view addSubview:headLabel];
_headImage =[[UIButton alloc]initWithFrame:CGRectMake(120+(width-120-30-150)/2.0, 200, 150, 150)];
_headImage.backgroundColor =[UIColor yellowColor];
[_headImage addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_headImage];
UIButton *btn =[[UIButton alloc]initWithFrame:CGRectMake(100, 500, 200, 200)];
[btn setTitle:@"完成" forState:UIControlStateNormal];
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[btn addTarget:self action:@selector(pop) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}
- (void)pop
{
UserModel *model =[[UserModel alloc]init];
model.name=_nameField.text;
model.age=[NSNumber numberWithInteger:[_ageField.text integerValue]];
model.headImage=_image;
// [_delegate reloadDataMath];//代理
[[DBManager shareManager] insertModel:model];
_rdBlock();
[self.navigationController popViewControllerAnimated:YES];
}
- (void)btnClick:(UIButton *)btn
{
NSLog(@"2");
UIActionSheet *acSheet=[[UIActionSheet alloc]initWithTitle:@"选择图片来源" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相册",@"相机", nil];
[acSheet showInView:self.view];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex==0) {
// NSLog(@"调用相册");
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
//isSourceTypeAvailable yes:可以调用 NO 不可调用
// UIImagePickerControllerSourceTypePhotoLibrary 调用相册 UIImagePickerControllerSourceTypeCamera 掉用相机
UIImagePickerController *pick =[[UIImagePickerController alloc]init];
//第二步:实例化 UIImagePickerController
pick.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;// 第三步,告诉pick对象调用的是系统的相册
pick.delegate=self;//第四步,设置代理
pick.allowsEditing=YES;//第五步,自动修图
[self presentViewController:pick animated:YES completion:^{}];
}
else
{
NSLog(@"调用相机失败");
}
}else if(buttonIndex ==1)
{
// NSLog(@"调用相机");
}
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSLog(@"%@",info);
NSString *mediaType =[info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
[_headImage setImage:[info objectForKey:UIImagePickerControllerEditedImage] forState:UIControlStateNormal];
_image=[info objectForKey:UIImagePickerControllerEditedImage];
}
[picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
// [self dismissViewControllerAnimated:YES completion:nil];
[picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
NSString *sql =@"select * from userInfo where id =?"; FMResultSet *set = [_fmdb executeQuery:sql,idOne]; return [set next]; } @end
转载于:https://www.cnblogs.com/0515offer/p/4696302.html
相关资源:数据结构—成绩单生成器