UI21_豆瓣数据库

添加数据库要记得
AppDelegate.h

#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;


@end

AppDelegate.m

#import "AppDelegate.h"
#import "RootViewController.h"

@interface AppDelegate ()

@end

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

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    [_window release];

    RootViewController *rootVC = [[RootViewController alloc] init];
    UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:rootVC];
    self.window.rootViewController = naVC;
    [naVC release];
    [rootVC release];

    return YES;
}

RootViewController.h

#import <UIKit/UIKit.h>

@interface RootViewController : UIViewController

@end

RootViewController.m

#import "RootViewController.h"
#import "AFNetworking.h"
#import "Movie.h"
#import "MovieDetailViewController.h"

@interface RootViewController ()<UITableViewDataSource, UITableViewDelegate>
@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, retain)NSMutableArray *movieArr;

@end

@implementation RootViewController
- (void)dealloc
{
    [_tableView release];
    [_movieArr release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"电影";
    self.view.backgroundColor = [UIColor whiteColor];


//    [self createTableView];
    [self.view addSubview:self.tableView];
    [self createData];


}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    MovieDetailViewController *mdVC = [[MovieDetailViewController alloc] init];
    [self.navigationController pushViewController:mdVC animated:YES];
    [mdVC release];

    mdVC.movie = self.movieArr[indexPath.row];

}

- (UITableView *)tableView {
    if (!_tableView) {
        self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
        self.tableView.dataSource = self;
        self.tableView.delegate = self;
    }
    return _tableView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.movieArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reuse = @"reuse";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (!cell) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse] autorelease];
    }
    Movie *movie = self.movieArr[indexPath.row];
    cell.textLabel.text = movie.movieName;

    return cell;
}

- (void)createData {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:@"http://project.lanou3g.com/teacher/yihuiyun/lanouproject/movielist.php" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"%@", responseObject);
        NSDictionary *dic = responseObject;
        self.movieArr = [NSMutableArray array];
        for (NSDictionary *temp in dic[@"result"]) {
            Movie *movie = [[Movie alloc] init];
            [movie setValuesForKeysWithDictionary:temp];
            [self.movieArr addObject:movie];
            [movie release];
//            NSLog(@"%@", movie.movieName);
//            NSLog(@"%ld", self.movieArr.count);
        }

        [self.tableView reloadData];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        NSLog(@"%@", error);
    }];

}

MovieDetailViewController.h

#import <UIKit/UIKit.h>
@class Movie;

@interface MovieDetailViewController : UIViewController
@property(nonatomic, retain)Movie *movie;

@end

MovieDetailViewController.m

#import "MovieDetailViewController.h"
#import "Movie.h"
#import "DataBaseHandle.h"

@interface MovieDetailViewController ()

@end

@implementation MovieDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = self.movie.movieName;
    [[DataBaseHandle shareDataBaseHandle] createTable];
    //  用一个枚举类型的变量接收结果, 变量去比较
    SelectMovie result = [[DataBaseHandle shareDataBaseHandle] isHaveInTable:self.movie];
    if (result == InTable) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"已收藏" style:UIBarButtonItemStylePlain target:self action:@selector(saveMovie:)];
    } else if (result == NotInTable) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"收藏" style:UIBarButtonItemStylePlain target:self action:@selector(saveMovie:)];
    } else {
        NSLog(@"出错");
    }

    //  查看所有已收藏的电影
    NSMutableArray *arr = [[DataBaseHandle shareDataBaseHandle] selectAllMovie];
    NSLog(@"%ld", arr.count);



}
- (void)saveMovie:(UIBarButtonItem *)button {
    if ([button.title isEqualToString:@"收藏"]) {
        [[DataBaseHandle shareDataBaseHandle] saveMovieInDB:self.movie];
        button.title = @"已收藏";
    } else {
        [[DataBaseHandle shareDataBaseHandle] deleteMovieInDB:self.movie];
        button.title = @"收藏";
    }
}

DataBaseHandle.h

#import <Foundation/Foundation.h>
#import <sqlite3.h>
#import "Movie.h"

typedef NS_ENUM(NSUInteger, SelectMovie) {
    InTable,
    NotInTable,
    SelectError,
};

@interface DataBaseHandle : NSObject
{
    sqlite3 *dbPoint;
}

+ (instancetype)shareDataBaseHandle;

- (void)openDB;
- (void)createTable;
- (SelectMovie)isHaveInTable:(Movie *)movie;
//  收藏
- (void)saveMovieInDB:(Movie *)movie;
//  取消收藏, 直接删除
- (void)deleteMovieInDB:(Movie *)movie;
//  查找全部收藏电影
- (NSMutableArray *)selectAllMovie;



@end

DataBaseHandle.m

#import "DataBaseHandle.h"

@implementation DataBaseHandle

+ (instancetype)shareDataBaseHandle {
    static DataBaseHandle *handle;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        handle = [[DataBaseHandle alloc] init];
    });
    [handle openDB];
    [handle createTable];
    return handle;
}

- (void)openDB {
    //  1. 沙盒路径
    NSString *sandBoxPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    //  2. 拼接路径
    NSString *dbPath = [sandBoxPath stringByAppendingPathComponent:@"Movie.sqlite"];
    int result = sqlite3_open([dbPath UTF8String], &dbPoint);
    if (result == SQLITE_OK) {
        NSLog(@"打开成功");
    } else {
        NSLog(@"打开失败");
    }
    NSLog(@"%@", dbPath);

}

- (void)createTable {
//    NSString *sqlStr = @"create table if not exists movie(movieId text primary key, movieName text, pic_url text)";
    NSString *sqlStr = @"create table if not exists movie(movieId text, movieName text, pic_url text, flag integer)";
    int resutl = sqlite3_exec(dbPoint, [sqlStr UTF8String], nil, nil, nil);
//    if (resutl == SQLITE_OK) {
//        NSLog(@"创建表成功");
//    } else {
//        NSLog(@"创建表失败");
//    }

    resutl == SQLITE_OK ? NSLog(@"创建表成功") : NSLog(@"创建表失败");
}

- (SelectMovie)isHaveInTable:(Movie *)movie {
    //  除了openDBs, 都先写语句
//    NSString *sqlStr = [NSString stringWithFormat:@"select * from movie where movieId = '%@'", movie.movieId];
    NSString *sqlStr = [NSString stringWithFormat:@"select * from movie where movieId = '%@' and flag = '1'", movie.movieId];
    //  跟随指针
    sqlite3_stmt *stmt = nil;
    int resutl = sqlite3_prepare_v2(dbPoint, [sqlStr UTF8String], -1, &stmt, nil);
//    NSMutableArray *movieArr = [NSMutableArray array];
    if (resutl == SQLITE_OK) {
        NSLog(@"查询成功");
        if (sqlite3_step(stmt) == SQLITE_ROW) {
            //  注销跟随指针
            sqlite3_finalize(stmt);
            return InTable;
        } else {
            sqlite3_finalize(stmt);
            return NotInTable;
        }
    } else {
        NSLog(@"查询失败");
        sqlite3_finalize(stmt);
        return SelectError;
    }
}

- (void)saveMovieInDB:(Movie *)movie {
    NSString *sqlStr = [NSString stringWithFormat:@"insert into  movie (movieId, movieName, pic_url, flag) values ('%@', '%@', '%@', '1')", movie.movieId, movie.movieName, movie.pic_url];
    int result = sqlite3_exec(dbPoint, [sqlStr UTF8String], nil, nil, nil);
    if (result == SQLITE_OK) {
        NSLog(@"收藏成功");
    } else {
        NSLog(@"收藏失败");
    }

//    result == SQLITE_OK ? NSLog(@"收藏成功") : NSLog(@"收藏失败");
}

- (void)deleteMovieInDB:(Movie *)movie {
    //  物理删除
    NSString *sqlStr = [NSString stringWithFormat:@"delete from movie where movieId= '%@'", movie.movieId];
    int result = sqlite3_exec(dbPoint, [sqlStr UTF8String], nil, nil, nil);
    if (result == SQLITE_OK) {
        NSLog(@"删除成功");
    } else {
        NSLog(@"删除失败");
    }
//    result == SQLITE_OK ? NSLog(@"删除成功") : NSLog(@"删除失败");

    //  逻辑删除
//    NSString *sqlStr = [NSString stringWithFormat:@"update movie set flag = '0' where movieId = '%@'", movie.movieId];
}

- (NSMutableArray *)selectAllMovie {
    NSMutableArray *movieArr = [NSMutableArray array];
    NSString *sqlStr = @"select * from movie where flag = '1'";
//    NSString *sqlStr = @"select *from movie";
    //  跟随指针
    sqlite3_stmt *stmt = nil;
    //  执行查找
    int result = sqlite3_prepare_v2(dbPoint, [sqlStr UTF8String], -1, &stmt, nil);
    if (result == SQLITE_OK) {
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            Movie *movie = [[Movie alloc] init];
            movie.movieName = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 1)];
            movie.pic_url = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 2)];
            movie.movieId = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 0)];
            [movieArr addObject:movie];
            [movie release];
        }
    }

    sqlite3_finalize(stmt);
    return movieArr;
}

@end

Movie.h

#import <Foundation/Foundation.h>

@interface Movie : NSObject
@property(nonatomic, copy)NSString *movieId;
@property(nonatomic, copy)NSString *movieName;
@property(nonatomic, copy)NSString *pic_url;

@end

Movie.m

#import "Movie.h"

@implementation Movie

- (void)setValue:(id)value forUndefinedKey:(NSString *)key {

}

@end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值