UI:數據庫練習、濾鏡效果

相機處理濾鏡效果sql

濾鏡主要使用在相機的美顏。數據庫

#import "ViewController.h"
#import "ImageUtil.h"
#import "ColorMatrix.h"
@interface ViewController ()<UIActionSheetDelegate>

@property (nonatomic, strong) UIImageView *filterView;

@property (nonatomic, strong) UILabel *filterLabel;

@end

@implementation ViewController

- (UIImageView *)filterView
{
    if (_filterView == nil) {
        _filterView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 50.0f, self.view.frame.size.width, 200.0f)];
        _filterView.userInteractionEnabled = YES;
        //contentMode是用來設置圖片的顯示方式,如居中、居右,是否縮放。
        //特別注意:UIViewContentModeScaleToFill屬性會致使圖片變形。UIViewContentModeScaleAspectFit會保證圖片比例不變,並且所有顯示在ImageView中,這意味着ImageView會有部分空白。UIViewContentModeScaleAspectFill也會證圖片比例不變,可是是填充整個ImageView的,可能只有部分圖片顯示出來。
        //其它的當圖片的大小超過屏幕的尺寸時,只有部分顯示出來
        _filterView.contentMode = UIViewContentModeScaleToFill;
    }
    return _filterView;
}

- (UILabel *)filterLabel
{
    if (_filterLabel == nil) {
        _filterLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 300.0f, self.view.frame.size.width, 25.0f)];
        _filterLabel.backgroundColor = [UIColor clearColor];
        _filterLabel.textColor = [UIColor orangeColor];
        _filterLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _filterLabel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.title = @"濾鏡";
    if ([[[UIDevice currentDevice] systemVersion] floatValue] > 7.0f) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    self.filterView.image = [UIImage imageNamed:@"622.png"];
    [self.view addSubview:self.filterView];
    
    self.filterLabel.text = @"原圖";
    [self.view addSubview:self.filterLabel];
    
    UIButton *sender = [UIButton buttonWithType:UIButtonTypeCustom];
    [sender setTitle:@"濾鏡" forState:UIControlStateNormal];
    sender.frame = CGRectMake(self.view.frame.size.width/2.0f - 50.0f, 350.0f, 100.0f, 30.0f);
    sender.backgroundColor = [UIColor redColor];
    sender.layer.cornerRadius = 5.0f;
    [sender addTarget:self action:@selector(senderAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sender];
}

#pragma mark - senderAction 按鈕點擊事件
- (void)senderAction
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"濾鏡" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"原圖",@"LOMO",@"黑白",@"復古",@"哥特",@"銳化",@"淡雅",@"酒紅",@"清寧",@"浪漫",@"光暈",@"藍調",@"夢幻",@"夜色", nil];
    [actionSheet showInView:self.view];
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString *str = @"";
    switch (buttonIndex) {
        case 0:
            str = @"原圖";
            self.filterView.image = [UIImage imageNamed:@"622.png"];
            break;
        case 1:
            str = @"LOMO";
            self.filterView.image = [ImageUtil imageWithImage:[UIImage imageNamed:@"622.png"] withColorMatrix:colormatrix_lomo];
            break;
        case 2:
            str = @"黑白";
            self.filterView.image = [ImageUtil imageWithImage:[UIImage imageNamed:@"622.png"] withColorMatrix:colormatrix_heibai];
            break;
        case 3:
            str = @"復古";
            self.filterView.image = [ImageUtil imageWithImage:[UIImage imageNamed:@"622.png"] withColorMatrix:colormatrix_huajiu];
            break;
        case 4:
            str = @"哥特";
            self.filterView.image = [ImageUtil imageWithImage:[UIImage imageNamed:@"622.png"] withColorMatrix:colormatrix_gete];
            break;
        case 5:
            str = @"銳化";
            self.filterView.image = [ImageUtil imageWithImage:[UIImage imageNamed:@"622.png"] withColorMatrix:colormatrix_ruise];
            break;
        case 6:
            str = @"淡雅";
            self.filterView.image = [ImageUtil imageWithImage:[UIImage imageNamed:@"622.png"] withColorMatrix:colormatrix_danya];
            break;
        case 7:
            str = @"酒紅";
            self.filterView.image = [ImageUtil imageWithImage:[UIImage imageNamed:@"622.png"] withColorMatrix:colormatrix_jiuhong];
            break;
        case 8:
            str = @"清寧";
            self.filterView.image = [ImageUtil imageWithImage:[UIImage imageNamed:@"622.png"] withColorMatrix:colormatrix_qingning];
            break;
        case 9:
            str = @"浪漫";
            self.filterView.image = [ImageUtil imageWithImage:[UIImage imageNamed:@"622.png"] withColorMatrix:colormatrix_langman];
            break;
        case 10:
            str = @"光暈";
            self.filterView.image = [ImageUtil imageWithImage:[UIImage imageNamed:@"622.png"] withColorMatrix:colormatrix_guangyun];
            break;
        case 11:
            str = @"藍調";
            self.filterView.image = [ImageUtil imageWithImage:[UIImage imageNamed:@"622.png"] withColorMatrix:colormatrix_landiao];
            break;
        case 12:
            str = @"夢幻";
            self.filterView.image = [ImageUtil imageWithImage:[UIImage imageNamed:@"622.png"] withColorMatrix:colormatrix_menghuan];
            break;
        case 13:
            str = @"夜色";
            self.filterView.image = [ImageUtil imageWithImage:[UIImage imageNamed:@"622.png"] withColorMatrix:colormatrix_yese];
            break;
            
        default:
            break;
    }
    
    self.filterLabel.text = str;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
View Code 基於 storyboard編寫的 濾鏡效果demo

 

代碼:數組

#pragma mark (.h文件)--------------------------------------------------------------------------------------------------------


#pragma mark (.m文件)--------------------------------------------------------------------------------------------------------


#import "AppDelegate.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

- (void)dealloc {
    [_window release];
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    return YES;
}
}//這裏面並無寫一個 Self.window.rootViewController = xx.vc ;是由於用了storyBoard,而後修改了程序的主入口
View Code Appdelegate文件
#pragma mark (.h文件)--------------------------------------------------------------------------------------------------------


#import <UIKit/UIKit.h>

@interface ContactListController : UITableViewController

@end


#pragma mark (.m文件)--------------------------------------------------------------------------------------------------------
#import "ContactListController.h"
#import "DataBaseHelper.h"
#import "ContactDetailController.h"
#import "AddContactController.h"
#import "Contact.h"
#import "ContactListCell.h"
#import "FMDatabase.h"//第三方(數據庫操做類)
#import "DataBaseHelper.h"


//指定代理對象所在的類服從協議_04
@interface ContactListController ()<updateDelegate>
@property (nonatomic, retain) FMDatabase *database;//存儲數據庫操做對象
@property (nonatomic, retain) NSMutableArray *dataSource;//存儲數據源

@end

@implementation ContactListController
#pragma mark -lazy loading-
- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        self.dataSource = [NSMutableArray arrayWithCapacity:0];
    }
    return [[_dataSource retain] autorelease];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.leftBarButtonItem = self.editButtonItem;
    //1.建立數據庫
    [self createDataBase];
    //2.建立表
    [self createTable];
    //3.讀取數據
    [self selectDataFromDataBase];
}

-(void)setEditing:(BOOL)editing animated:(BOOL)animated{
    [super setEditing:editing animated:animated];
    if (!editing) {// NO 編輯完成
        self.view.userInteractionEnabled = NO;
        //將修改後的數據返回到上一個界面
        
    }
}
#pragma mark -handle DataBase -
- (void)createDataBase {
    //數據庫操做對象
    self.database = [FMDatabase databaseWithPath:[self getFilePath]];
}
//建立表
- (void)createTable {
    //1.打開數據庫
    if (![self.database open]) {
        return;
    }
    //2.經過SQL語句操做數據庫 (建立表)
    //executeUpdate: 除了查詢指令,其餘的都用這個方法
    [self.database executeUpdate:@"create table if not exists Contacts(con_id integer primary key autoincrement, con_name text, con_gender text, con_age integer, con_phoneNum text, con_image blob)"];
    //3.關閉數據庫
    [self.database close];
}
//讀取數據
- (void)selectDataFromDataBase {
    //1.打開數據庫
    if (![self.database open]) {
        return;
    }
    //2.經過SQL語句執行查詢操做
    FMResultSet *result = [self.database executeQuery:@"select * from Contacts"];
    while ([result next]) {
        NSInteger ID = [result intForColumn:@"con_id"];
        NSString *name = [result stringForColumn:@"con_name"];
        NSString *gender = [result stringForColumn:@"con_gender"];
        NSInteger age = [result intForColumn:@"con_age"];
        NSString *phoneNum = [result stringForColumn:@"con_phoneNum"];
        NSData *data = [result dataForColumn:@"con_image"];
        UIImage *image = [UIImage imageWithData:data];
        //把數據封裝到Contact對象裏
        Contact *per = [[Contact alloc] initWithId:ID name:name gender:gender age:age phoneNum:phoneNum photoImage:image];
        //存放到數組中
        [self.dataSource addObject:per];
    }
    //3.關閉數據庫
    [self.database close];
}

- (NSString *)getFilePath {
   NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSLog(@"%@", docPath);
    return [docPath stringByAppendingPathComponent:@"DB.sqlite"];
}

//插入一條數據
- (void)insertIntoDataBaseWithContact:(Contact *)contact {
    //1.打開數據庫
    if (![self.database open]) {
        return;
    }
    //2.經過SQL語句操做數據庫(插入一條數據)
    NSData *data = UIImagePNGRepresentation(contact.photoImage);
    
    [self.database executeUpdate:@"insert into Contacts(con_name, con_gender, con_age, con_phoneNum, con_image) values(?, ?, ?, ?, ?)", contact.name, contact.gender, @(contact.age), contact.phoneNum, data];
    //3.關閉數據庫
    [self.database close];
} 


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return _dataSource.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ContactListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse" forIndexPath:indexPath];
    Contact *per = self.dataSource[indexPath.row];
    // Configure the cell...
    cell.nameLabel.text = per.name;
    cell.phoneNumLabel.text = per.phoneNum;
    return cell;
}




// 提交編輯的方法
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
       //1.數據源的刪除
        Contact * per = self.dataSource[indexPath.row];
        //從數據庫刪除該條數據
        [self deleteFromDataBaseWithContact:per];
        //從數組裏移除
        [self.dataSource removeObjectAtIndex:indexPath.row];
        
       //2.界面的刪除
        //當前只有一個分區,因此不判斷分區
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
    
    }   
}
//刪除一條數據
-(void)deleteFromDataBaseWithContact:(Contact *)contact{
    BOOL isOpen = [self.database open];
    if (!isOpen) {
        return;
    }
    [self .database executeUpdate:@"delete from Contacts where con_id = ?",@(contact.con_id)];
    //關閉數據庫
    [self.database close];
}

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

//用於刷新數據
/*下面插入數據後已經刷新了數據
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.dataSource removeAllObjects];
    [self selectDataFromDataBase];
    [self.tableView reloadData];
    NSLog(@"%@@@@@",((Contact *)self.dataSource[0]).name);
}
*/

#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation


//使用 StoryBoard 進行頁面跳轉的時候,它會自動的走這個方法。在這個方法咱們能夠作一些須要的相應的操做方法。
//參數:第一個參數 segue 就是跳轉的線 第二個參數 sender 就是咱們跳轉的時候要傳的參數 destinationViewController是一個導航控制器。
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    __block ContactListController *vc = self;
    if ([segue.identifier isEqualToString:@"add"]) {
        AddContactController *addVC = [segue.destinationViewController viewControllers][0];
//        [segue.destinationViewController viewControllers][0]就是獲得導航控制器所管理的視圖控制器
        addVC.AddBlock = ^(Contact *contact) {
            //方到數組中
            [vc.dataSource addObject:contact];
            //本地數據持久化,放入本地數據庫的表中
            [vc insertIntoDataBaseWithContact:contact];
            //刷新數據,界面就要從新讀出頁面的內容
            [vc.tableView reloadData];
        };
    } else {
//        ContactDetailController *detailVC = [[ContactDetailController alloc] init];
        ContactDetailController * detailVc = segue.destinationViewController;
        NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];//sender 此時是選中的cell
        //屬性傳值
        detailVc.contact = self.dataSource[indexPath.row];
        //設置代理對象_03
        detailVc.delegate = self;
        
    }
}

//實現協議_05
-(void)updateDataWithContact:(Contact *)contact{
    //執行更新操做 跟新數據庫表裏的信息
    [self updateFromDataBaseWithContact:contact];
    NSLog(@"//執行更新操做 跟新數據庫表裏的信息");
    //刷新數據
    [self.tableView reloadData];
}

//更新一條數據
- (void)updateFromDataBaseWithContact:(Contact *)contact{
    //1.打開數據庫
    BOOL isOpen = [self.database open];
    if (!isOpen) {
        return;
    }
    NSData * data = UIImagePNGRepresentation(contact.photoImage);
    //2.執行SQL語句操做數據庫
    BOOL isSuccess =[self.database executeUpdate:@"update Contacts set con_name = ?, con_gender = ?,con_age = ?,con_phoneNum = ?,con_image = ? where con_id = ?",contact.name,contact.gender,@(contact.age),contact.phoneNum,data,@(contact.con_id)];//注意把 age 轉化爲對象
    if (isSuccess) {
        NSLog(@"%@",isSuccess ? @"更新成功":@"更新失敗");
    }else{
        NSLog(@"失敗");
    }
    //3.關閉數據庫
    [self.database close];
}
/*
 數據庫操做類
 數據庫查詢類
 數據庫在多線程下的操做類
 
 使用 FMDB
 FMDatabase :1.建立數據庫,咱們只須要提供一個數據庫路徑
             2.建立表
             3.用數據庫對象去執行相應的操做 executeUpdate(只能操做對象)  executeQure
               操做有,建立表,增刪改查
                 1).打開數據庫
                 2).經過給定的SQL語句操做數據庫
                 3).關閉數據庫
 */

@end
View Code ContactListController文件
#pragma mark (.h文件)--------------------------------------------------------------------------------------------------------


#import <UIKit/UIKit.h>
#import "Contact.h"

//指定代理協議_01
@protocol updateDelegate <NSObject>

-(void)updateDataWithContact:(Contact *)contact;

@end

//下面屬性是從 storyBoard 裏面關聯的屬性
@interface ContactDetailController : UIViewController
@property (retain, nonatomic) IBOutlet UITextField *nameTf;
@property (retain, nonatomic) IBOutlet UITextField *genderLabel;
@property (retain, nonatomic) IBOutlet UITextField *phonelabel;
@property (retain, nonatomic) IBOutlet UIImageView *phontoView;

//定義代理屬性_02  注意這裏不寫 copy 要寫 assign  Block 中須要爲 Copy
@property(nonatomic,assign)id<updateDelegate>delegate;

//定義屬性 接收首頁傳來的model
@property (nonatomic, retain) Contact *contact;
@end


#pragma mark (.m文件)--------------------------------------------------------------------------------------------------------



#import "ContactDetailController.h"

@interface ContactDetailController ()

@end

@implementation ContactDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
    self.view.userInteractionEnabled = NO;
    self.nameTf.text = self.contact.name;
    self.phonelabel.text = self.contact.phoneNum;
    self.phontoView.image = self.contact.photoImage;
}
-(void)setEditing:(BOOL)editing animated:(BOOL)animated{
    [super setEditing:editing animated:animated];
    self.view.userInteractionEnabled = editing;//根據參數去肯定用戶是否能夠操做控件的編輯
    if (!editing) {
        //將修改後的聯繫人返回到上一界面
//        NSString * name = self.nameTf.text;
//        NSString * gender = self.genderLabel.text;
//        NSString * phoneNum = self.phonelabel.text;
//        UIImage * image = self.phontoView.image;
//        Contact * per = [[Contact alloc]initWithId:self.contact.con_id name:name gender:gender age:10 phoneNum:phoneNum photoImage:image];//這是新建的一個
        //優化
        self.contact.name = self.nameTf.text;
        self.contact.gender = self.genderLabel.text;
        self.contact.phoneNum = self.phonelabel.text;
        self.contact.photoImage =self.phontoView.image;
        //傳回到上一界面_06
        if (self.delegate && [self.delegate respondsToSelector:@selector(updateDataWithContact:)]) {
//            [self.delegate updateDataWithContact:per];
            [self.delegate updateDataWithContact:self.contact];
        }else{
            NSLog(@"錯誤的");
        }
    }
}
- (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.
}
*/

- (void)dealloc {
    [_nameTf release];
    [_genderLabel release];
    [_phonelabel release];
    [_phontoView release];
    [super dealloc];
}
@end
View Code ContactDetailController文件
#pragma mark (.h文件)--------------------------------------------------------------------------------------------------------

#import <UIKit/UIKit.h>
@class Contact;
@interface AddContactController : UIViewController

@property (nonatomic, copy) void(^AddBlock)(Contact *);


@end



#pragma mark (.m文件)--------------------------------------------------------------------------------------------------------

//
//  AddContactController.m

#import "AddContactController.h"
#import "Contact.h"

@interface AddContactController ()
@property (retain, nonatomic) IBOutlet UIImageView *photoImageView;
@property (retain, nonatomic) IBOutlet UITextField *nameTF;
@property (retain, nonatomic) IBOutlet UITextField *genderTF;
@property (retain, nonatomic) IBOutlet UITextField *phoneTF;

@end

@implementation AddContactController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (IBAction)handleCancel:(id)sender {
    if (![self.nameTF.text isEqualToString:@""] || ![self.phoneTF.text isEqualToString:@""]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"肯定放棄保存嗎" delegate:self cancelButtonTitle:@"" otherButtonTitles:@"肯定", nil];
        [alert show];
        [alert release];
        //其餘操做
    }else if ([self.nameTF.text isEqualToString:@""] && [self.phoneTF.text isEqualToString:@""]) {
        NSLog(@"返回返回");
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    }
}
- (IBAction)handelDone:(id)sender {
    NSString *name = self.nameTF.text;
    NSString *gender = self.genderTF.text;
    NSString *phone = self.phoneTF.text;
    Contact *contact = [[Contact alloc] initWithId:0 name:name gender:gender age:12 phoneNum:phone photoImage:nil];
        //傳到上一界面
    self.AddBlock(contact);
    
    /*
    if ([self.nameTF.text isEqualToString:@""] && [self.phoneTF.text isEqualToString:@""]) {
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
    }
     */
    [self 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.
}
*/

- (void)dealloc {
    [_photoImageView release];
    [_nameTF release];
    [_genderTF release];
    [_phoneTF release];
    [super dealloc];
}
@end
View Code AddContactController文件
#pragma mark (.h文件)--------------------------------------------------------------------------------------------------------


#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface Contact : NSObject
@property (nonatomic, assign) NSInteger con_id;
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *gender;
@property (nonatomic, assign) NSInteger age;
@property (nonatomic, copy) NSString *phoneNum;
@property (nonatomic, retain) UIImage *photoImage;

//初始化方法
- (instancetype)initWithId:(NSInteger)ID name:(NSString *)name gender:(NSString *)gender age:(NSInteger )age phoneNum:(NSString *)phoneNum photoImage:(UIImage *)photoImage;


@end


#pragma mark (.m文件)--------------------------------------------------------------------------------------------------------


#import "Contact.h"

@implementation Contact
- (instancetype)initWithId:(NSInteger)ID name:(NSString *)name gender:(NSString *)gender age:(NSInteger)age phoneNum:(NSString *)phoneNum photoImage:(UIImage *)photoImage {
    self = [super init];
    if (self) {
        self.con_id = ID;
        self.name = name;
        self.gender = gender;
        self.age = age;
        self.phoneNum = phoneNum;
        self.photoImage = photoImage;
    }
    return self;
}

- (void)dealloc {
    self.name = nil;
    self.gender = nil;
    self.phoneNum = nil;
    self.photoImage = nil;
    [super dealloc];
}
@end
View Code Contact文件
#pragma mark (.h文件)--------------------------------------------------------------------------------------------------------

#import <UIKit/UIKit.h>

@interface ContactListCell : UITableViewCell

@property (retain, nonatomic) IBOutlet UIImageView *photoImage;
@property (retain, nonatomic) IBOutlet UILabel *nameLabel;
@property (retain, nonatomic) IBOutlet UILabel *phoneNumLabel;
@end


#pragma mark (.m文件)--------------------------------------------------------------------------------------------------------

#import "ContactListCell.h"

@implementation ContactListCell

- (void)awakeFromNib {
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)dealloc {
    [_photoImage release];
    [_nameLabel release];
    [_phoneNumLabel release];
    [super dealloc];
}
@end
View Code ContactListCell文件
#pragma mark (.h文件)--------------------------------------------------------------------------------------------------------

#import <Foundation/Foundation.h>
#import <sqlite3.h>
/**
 *  該類是數據庫管理類。提供兩個功能:
 1.打開數據庫
 2.關閉數據庫
 
 導入libsqlite3.0.dylib動態連接庫,而後導入sqlite3.h頭文件
 */
@interface DataBaseManager : NSObject
//打開數據庫
+ (sqlite3 *)openDataBase;

//關閉數據庫
+ (void)closeDataBase;

@end


#pragma mark (.m文件)--------------------------------------------------------------------------------------------------------


#import "DataBaseManager.h"

static sqlite3 *db = nil;//存儲數據庫對象

@implementation DataBaseManager
//打開數據庫

+ (sqlite3 *)openDataBase {
    //優化 對於數據庫操做,咱們只打開一次數據庫就能夠了。
    //若是sqlite對象不爲空,說明以前打開過,直接返回數據庫地址就能夠了。
    if (db) {
        return db;
    }
    
    //1.獲取數據庫文件的路徑
    NSString *filePath = [self getFilePath];
    //2.打開數據庫
    sqlite3_open([filePath UTF8String], &db);
    return db;
}

//關閉數據庫
+ (void)closeDataBase {
    if (db) {
        sqlite3_close(db);
        db = nil;
    }
}

+ (NSString *)getFilePath {
    //1.獲取Documents文件夾路徑
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSLog(@"%@", path);
    //2.拼接上數據文件的路徑
    NSString *dataPath = [path stringByAppendingPathComponent:@"DB.sqlite"];
    return dataPath;
}

@end
View Code DataBaseManager文件
#pragma mark (.h文件)--------------------------------------------------------------------------------------------------------

#import <Foundation/Foundation.h>
#import <sqlite3.h>
@class Contact;
/**
 *  數據庫的操做類
    對數據庫進行建立表,插入,刪除,更新,查詢操做,從數據庫獲取數據,處理數據
 */
@interface DataBaseHelper : NSObject
//單例方法
+ (DataBaseHelper *)defaultDBHelper;

+ (void)createTableInDataBase;//建立表的操做

+ (void)selectFromDataBase;  //查詢數據的操做

+ (void)insertIntoDataBaseWithContact:(Contact *)contact; //插入一條數據的操做

+ (void)updateFromDataBaseWithContact:(Contact *)contact; //更新一條數據的操做

+ (void)deleteFromDataBaseWithContact:(Contact *)contact; //刪除一條數據的操做
//獲取惟一的標識
+ (NSInteger)getNumber;


//提供相應的方法給對應的controller

@end

//添加分類 用於建立指令集
@interface DataBaseHelper (CreateStatement)
+ (sqlite3_stmt *)createTableStatement;
+ (sqlite3_stmt *)insertStatement;
+ (sqlite3_stmt *)updateStatement;
+ (sqlite3_stmt *)selectStatement;
+ (sqlite3_stmt *)deleteStatement;
/*
1.打開數據庫
2.建立指令集
3.建立SQL語句
4.語法檢查
 */
@end


#pragma mark (.m文件)--------------------------------------------------------------------------------------------------------

#import "DataBaseHelper.h"
#import "DataBaseManager.h"
#import "Contact.h"
/**
 *  1.打開數據庫
    2.建立指令集
    3.建立SQL語句
    4.語法檢查
    5.獲取指令集
    (6.若是有參數,須要綁定參數)
    7.執行SQL語句
    8.釋放資源
    9.關閉數據庫
 */
@implementation DataBaseHelper
//單例方法
static DataBaseHelper *helper = nil;
+ (DataBaseHelper *)defaultDBHelper {
    @synchronized(self) {
        if (!helper) {
            helper = [[DataBaseHelper alloc] init];
            //程序每次運行,只從數據庫裏讀取一次數據便可
            [self createTableInDataBase];//建立表
            [self selectFromDataBase];//讀取數據
        }
    }
    return helper;
}
//建立表的操做
+ (void)createTableInDataBase {
    //5.獲取指令集
    sqlite3_stmt *stmt = [self createTableStatement];
    //6.若是有參數,須要綁定參數
    //7.執行SQL語句 執行數據庫操做
    if (sqlite3_step(stmt) == SQLITE_DONE) {
        NSLog(@"建立表成功");
    }
    //8.釋放資源
    sqlite3_finalize(stmt);
    //9.關閉數據庫
    [DataBaseManager closeDataBase];
}

+ (void)selectFromDataBase {
    
}
//插入
+ (void)insertIntoDataBaseWithContact:(Contact *)contact {
    //5.獲取指令集
    sqlite3_stmt *stmt = [self insertStatement];
    //(6.若是有參數,須要綁定參數)
    //第一個:指令集; 第二個:第幾個問號; 第三個:綁定的數據
    
    sqlite3_bind_int(stmt, 1, (int)contact.con_id);
    //第一個:指令集; 第二個:第幾個問號; 第三個:綁定的數據; 第四個:是否限制長度 第五個:預留參數
    sqlite3_bind_text(stmt, 2, [contact.name UTF8String], -1, nil);
    sqlite3_bind_text(stmt, 3, [contact.gender UTF8String], -1, nil);
    sqlite3_bind_int(stmt, 4, (int)contact.age);
    sqlite3_bind_text(stmt, 5, [contact.phoneNum UTF8String], -1, nil);
    

    NSData *data = UIImagePNGRepresentation(contact.photoImage);
    //綁定二進制數據
    sqlite3_bind_blob(stmt, 6, data.bytes, (int)data.length, nil);
    
    //7.執行SQL語句
    if (sqlite3_step(stmt) == SQLITE_DONE) {
        NSLog(@"插入數據成功");
    }
    //8.釋放資源
    sqlite3_finalize(stmt);
    //9.關閉數據庫
    [DataBaseManager closeDataBase];
}

+ (void)updateFromDataBaseWithContact:(Contact *)contact {
    //5.獲取更新數據指令集
    sqlite3_stmt *stmt = [self updateStatement];
    //6.綁定參數 01:指令集 02:第幾個問號 03:綁定的數據
    //01 指令集 02第幾個問號 03綁定的數據(C語言) 04是否限制長度 05預留參數
    sqlite3_bind_text(stmt, 1, [contact.name UTF8String], -1, nil);
    sqlite3_bind_text(stmt, 2, [contact.gender UTF8String], -1, nil);
    sqlite3_bind_int(stmt, 3, (int)contact.age);
    sqlite3_bind_text(stmt, 4, [contact.phoneNum UTF8String], -1, nil);
    
    //綁定二進制數據
    NSData *data = UIImagePNGRepresentation(contact.photoImage);
    sqlite3_bind_blob(stmt, 5, data.bytes, (int)data.length, nil);
    
    sqlite3_bind_int(stmt, 6, (int)contact.con_id);
    
    //7.執行SQL語句
    if (sqlite3_step(stmt) == SQLITE_DONE) {
        NSLog(@"修改數據成功");
    }
    //8.釋放資源
    sqlite3_finalize(stmt);
    //9.關閉數據庫
    [DataBaseManager closeDataBase];
}

+ (void)deleteFromDataBaseWithContact:(Contact *)contact {
    sqlite3_stmt *stmt = [self deleteStatement];
    sqlite3_bind_int(stmt, 1, (int)contact.con_id);
    if (sqlite3_step(stmt) == SQLITE_DONE) {
        NSLog(@"刪除數據成功");
    }
    sqlite3_finalize(stmt);
    [DataBaseManager closeDataBase];

}
//獲取惟一的標識
//+ (NSInteger)getNumber {
//    
//}

@end


//分類的實現部分
@implementation DataBaseHelper (CreateStatement)
+ (sqlite3_stmt *)createTableStatement {
    //1.打開數據庫
    sqlite3 *db = [DataBaseManager openDataBase];
    //2.建立指令集
    sqlite3_stmt *stmt = nil;
    //3.建立SQL語句
    NSString *creatTable = @"create table if not exists Contact(con_id integer primary key autoincrement, con_name text, con_gender text, con_age integer, con_phoneNum text, con_image blob)";
    //4.語法檢查 檢查數據庫是否打開成功,檢查SQL語句是否正確
    /**
     *  第一個參數:數據庫對象
        第二個參數:SQL語句,
        第三個參數:是否限制SQL語句的長度
        第四個參數:指令集地址
        第五個參數:預留參數
     */
    int flag = sqlite3_prepare_v2(db, [creatTable UTF8String], -1, &stmt, 0);
    if (flag == SQLITE_OK) {
        NSLog(@"建立表的指令集成功");
    }
    return stmt;//返回指令集
}

+ (sqlite3_stmt *)insertStatement {
    //1.打開數據庫
    sqlite3 *db = [DataBaseManager openDataBase];
    //2.建立指令集
    sqlite3_stmt *stmt = nil;
    //3.建立SQL語句
    NSString *insertSQL = @"insert into Contact(con_id, con_name, con_gender, con_age, con_phoneNum, con_image) values(?, ?, ?, ?, ?, ?)";
    //4.語法檢查
    int flag = sqlite3_prepare_v2(db, [insertSQL UTF8String], -1, &stmt, 0);
    if (flag == SQLITE_OK) {
        NSLog(@"插入語法正確");
    }
    return stmt;
    
}
+ (sqlite3_stmt *)updateStatement {
    sqlite3 *db = [DataBaseManager openDataBase];
    NSString *updateSQL = @"update Contact set con_name = ?, con_gender = ?, con_age = ?, con_phone = ?, con_image = ? where con_id = ?";
    sqlite3_stmt *stmt = nil;
    int flag = sqlite3_prepare_v2(db, [updateSQL UTF8String], -1, &stmt, 0);
    if (SQLITE_OK == flag) {
        NSLog(@"更新數據成功");
    }
    return stmt;
}
+ (sqlite3_stmt *)selectStatement {
    sqlite3 *db = [DataBaseManager openDataBase];
    NSString *selectSQL = @"select * from Contact";
    sqlite3_stmt *stmt = nil;
    int flag = sqlite3_prepare_v2(db, [selectSQL UTF8String], -1, &stmt, 0);
    if (SQLITE_OK == flag) {
        NSLog(@"查詢數據成功");
    }
    return stmt;
}
+ (sqlite3_stmt *)deleteStatement {
    sqlite3 *db = [DataBaseManager openDataBase];
    NSString *deleteSQL = @"delete from Contact where con_id = ?";
    sqlite3_stmt *stmt = nil;
    int flag = sqlite3_prepare_v2(db, [deleteSQL UTF8String], -1, &stmt, 0);
    if (SQLITE_OK == flag) {
        NSLog(@"刪除數據成功");
    }
    return stmt;
}


@end
View Code DataBaseHelper文件

 

數據庫更新操做的時候,注意是對對象的更新,若是不是對象,就要轉化爲對象(由於底層是用C語言寫的)。多線程

添加聯繫人咱們用的是 Block傳值。app

咱們使用第三方數據庫操做類 FMDB 的步驟:ide

#import "FMDatabase.h" 數據庫操做類優化

#import "FMResultSet.h" 數據庫查詢類ui

#import "FMDatabaseAdditions.h" 數據庫其餘附加方法atom

#import "FMDatabaseQueue.h"線程下的數據庫操做類spa

#import "FMDatabasePool.h"數據庫在多線程下的操做類

  使用 FMDB

 FMDatabase :1.建立數據庫,咱們只須要提供一個數據庫路徑

             2.建立表

             3.用數據庫對象去執行相應的操做 executeUpdate(只能操做對象)  executeQure

               操做有,建立表,增刪改查

                 1).打開數據庫

                 2).經過給定的SQL語句操做數據庫

                 3).關閉數據庫

 

必定要掌握下面的操做方法

*****************************************

*CocoaPods快速引入第三方類:
cd 拖入文件(cd 與文件名中間有空格)
pod init
pod search 須要引入的類
而後再podfile文件中粘貼上類的版本號
pod install --verbose --no-repo-update
*****************************************

 

注意:對於屬性的屬性在定義代理的屬性的時候要使用 assign ;在使用Block 的時候要使用Copy

相關文章
相關標籤/搜索