FMDB

//

//  AppDelegate.h

//  靠前瞎鸡儿信1

//

//  Created by 徐才茵 on 20/12/2018.

//  Copyright © 2018 徐才茵. All rights reserved.

//

#import

#import

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property(readonly,strong)NSPersistentContainer*persistentContainer;

- (void)saveContext;

@end


//

//  AppDelegate.m

//  靠前瞎鸡儿信1

//

//  Created by 徐才茵 on 20/12/2018.

//  Copyright © 2018 徐才茵. All rights reserved.

//

#import "AppDelegate.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {

    // Override point for customization after application launch.

    return YES;

}

- (void)applicationWillResignActive:(UIApplication*)application {

    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.

    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.

}

- (void)applicationDidEnterBackground:(UIApplication*)application {

    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.

    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

}

- (void)applicationWillEnterForeground:(UIApplication*)application {

    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.

}

- (void)applicationDidBecomeActive:(UIApplication*)application {

    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

}

- (void)applicationWillTerminate:(UIApplication *)application {

    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.

    // Saves changes in the application's managed object context before the application terminates.

    [selfsaveContext];

}

#pragma mark - Core Data stack

@synthesizepersistentContainer = _persistentContainer;

- (NSPersistentContainer *)persistentContainer {

    // The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.

    @synchronized (self) {

        if(_persistentContainer ==nil) {

            _persistentContainer = [[NSPersistentContainer alloc] initWithName:@"______1"];

            [_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {

                if(error !=nil) {

                    // Replace this implementation with code to handle the error appropriately.

                    // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.


                    /*

                     Typical reasons for an error here include:

                     * The parent directory does not exist, cannot be created, or disallows writing.

                     * The persistent store is not accessible, due to permissions or data protection when the device is locked.

                     * The device is out of space.

                     * The store could not be migrated to the current model version.

                     Check the error message to determine what the actual problem was.

                    */

                    NSLog(@"Unresolved error %@, %@", error, error.userInfo);

                    abort();

                }

            }];

        }

    }


    return_persistentContainer;

}

#pragma mark - Core Data Saving support

- (void)saveContext {

    NSManagedObjectContext *context =self.persistentContainer.viewContext;

    NSError *error =nil;

    if([context hasChanges] && ![context save:&error]) {

        // Replace this implementation with code to handle the error appropriately.

        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

        NSLog(@"Unresolved error %@, %@", error, error.userInfo);

        abort();

    }

}

@end



//

//  Model.h

//  靠前瞎鸡儿信1

//

//  Created by 徐才茵 on 20/12/2018.

//  Copyright © 2018 徐才茵. All rights reserved.

//

#import

NS_ASSUME_NONNULL_BEGIN

@interface Model : NSObject

@property(nonatomic,assign)int ID;

@property (nonatomic,strong)NSString *imgsrc,*title;

@end

NS_ASSUME_NONNULL_END




//

//  Model.m

//  靠前瞎鸡儿信1

//

//  Created by 徐才茵 on 20/12/2018.

//  Copyright © 2018 徐才茵. All rights reserved.

//

#import "Model.h"

@implementation Model

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


}

@end


//

//  DataModel.h

//  靠前瞎鸡儿信1

//

//  Created by 徐才茵 on 20/12/2018.

//  Copyright © 2018 徐才茵. All rights reserved.

//

#import

NS_ASSUME_NONNULL_BEGIN

@interfaceDataModel :NSObject

+(DataModel*)sharedDataHandle;

//增

-(void)addOneMovie:(id)movie;

//删

-(void)deleteMovieByID:(int)delID;

//查

-(id)getAllMovies;

@end

NS_ASSUME_NONNULL_END




//

//  DataModel.m

//  靠前瞎鸡儿信1

//

//  Created by 徐才茵 on 20/12/2018.

//  Copyright © 2018 徐才茵. All rights reserved.

//

#import "DataModel.h"

#import"FMDB.h"

#import "Model.h"

staticDataModel*_defaulthandle =nil;

@interface DataModel ()

@property(nonatomic,strong)FMDatabase*fMDB;  //

@end

@implementation DataModel

+(DataModel*)sharedDataHandle

{

    if (_defaulthandle == nil) {

        _defaulthandle = [[DataModel alloc] init];


    }

    return _defaulthandle;

}

+(instancetype)allocWithZone:(struct_NSZone*)zone

{

    if (_defaulthandle == nil) {

        _defaulthandle= [superallocWithZone:zone];

    }

    return _defaulthandle;

}

-(FMDatabase *)fMDB

{

    if(!_fMDB) {

        NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"movies.sqlite"];

        NSLog(@"path=====%@",path);


        _fMDB= [FMDatabasedatabaseWithPath:path];

        [selfinitTable];

    }

    return _fMDB;

}

// 初始化数据表

-(void)initTable

{

    [_fMDBopen];


    [_fMDB executeUpdate:@"CREATE TABLE movie (id INTEGER PRIMARY KEY AUTOINCREMENT,title TEXT,imgsrc TEXT)"];



    [_fMDBclose];

}

-(void)addOneMovie:(Model*)movie

{

    [self.fMDBopen];


    // [self.fMDB executeUpdate:@"insert into movie (name,actor,date,price) values(?,?,?,?)",movie.name,movie.actor ,movie.date ,movie.price];


    [self.fMDB executeUpdateWithFormat:@"insert into movie (title,imgsrc) values(%@,%@)",movie.title,movie.imgsrc ];


    [self.fMDBclose];

}

-(void)deleteMovieByID:(int)delID

{

    [self.fMDBopen];


    [self.fMDB executeUpdateWithFormat:@"DELETE FROM movie WHERE id = %d",delID];


    [self.fMDBclose];

}

-(NSArray*)getAllMovies

{

    [self.fMDBopen];


    NSMutableArray *arr = [[NSMutableArray alloc] init];


    FMResultSet *result = [self.fMDB executeQuery:@"SELECT * FROM movie"];

    while([resultnext])

    {

        Model*movie = [[Modelalloc]init];

        [arraddObject:movie];


        movie.ID= [resultintForColumnIndex:0];

        movie.title= [resultstringForColumnIndex:1];

        movie.imgsrc= [resultstringForColumnIndex:2];


    }

    [self.fMDBclose];


    return[arrcopy];

}

@end




//

//  ZDYTableViewCell.h

//  靠前瞎鸡儿信1

//

//  Created by 徐才茵 on 20/12/2018.

//  Copyright © 2018 徐才茵. All rights reserved.

//

#import

#import "Model.h"

#import "DataModel.h"

NS_ASSUME_NONNULL_BEGIN

@interfaceZDYTableViewCell :UITableViewCell

@property (weak, nonatomic) IBOutlet UIImageView *imgv;

@property (weak, nonatomic) IBOutlet UILabel *lable;

- (void)loadData:(Model*)mod;

@end

NS_ASSUME_NONNULL_END





//

//  ZDYTableViewCell.m

//  靠前瞎鸡儿信1

//

//  Created by 徐才茵 on 20/12/2018.

//  Copyright © 2018 徐才茵. All rights reserved.

//

#import "ZDYTableViewCell.h"

@implementationZDYTableViewCell

- (void)loadData:(Model*)mod{

    if(mod) {

        self.lable.text=mod.title;

        self.imgv.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:mod.imgsrc]]];

    }


}

- (void)awakeFromNib {

    [super awakeFromNib];

    // Initialization code

}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {

    [supersetSelected:selectedanimated:animated];

    // Configure the view for the selected state

}

@end




//

//  ViewController.h

//  靠前瞎鸡儿信1

//

//  Created by 徐才茵 on 20/12/2018.

//  Copyright © 2018 徐才茵. All rights reserved.

//

#import

@interfaceViewController :UIViewController

@end




//

//  ViewController.m

//  靠前瞎鸡儿信1

//

//  Created by 徐才茵 on 20/12/2018.

//  Copyright © 2018 徐才茵. All rights reserved.

//

#import "ViewController.h"

#import "Model.h"

#import "AFNetworking.h"

#import "ZDYTableViewCell.h"

#import "DataModel.h"

#import "xqViewController.h"

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong)UITableView *table;

@property (nonatomic,strong)NSMutableArray *data;

- (IBAction)gotoxq:(id)sender;

@end

staticNSString*oj =@"cell";

@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];


//    [self.table registerClass:[ZDYTableViewCell class] forCellReuseIdentifier:oj];

    [self.table registerNib:[UINib nibWithNibName:@"ZDYTableViewCell" bundle:nil] forCellReuseIdentifier:oj];


    self.data=[[NSMutableArray alloc]init];


    [self CreateAFNet];


    [self.viewaddSubview:self.table];


    NSArray *allData = [[DataModel sharedDataHandle] getAllMovies];

     _data= [NSMutableArrayarrayWithArray:allData];

    [self.table reloadData];

}

- (UITableView*)table{

    if(!_table) {

        _table=[[UITableView alloc]initWithFrame:self.view.frame];

        _table.delegate=self;

        _table.dataSource=self;

    }


    return _table;

}

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section{

    return self.data.count;

}

-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{

    ZDYTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:oj];

    if(self.data.count>0) {

        Model*mod =self.data[indexPath.row];

        [cellloadData:mod];




    }

    returncell;

}

- (void)CreateAFNet{

    //  return;

    AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];

    [managerGET:@"http://c.m.163.com/nc/article/headline/T1348647853363/0-20.html" parameters:nil headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {

    }success:^(NSURLSessionDataTask*_Nonnulltask,id  _NullableresponseObject) {

        NSLog(@"%@",responseObject);


        for(NSDictionary*dicinresponseObject[@"T1348647853363"]) {

            Model*mod=[[Modelalloc]init];

            [modsetValuesForKeysWithDictionary:dic];

            [self.dataaddObject:mod];

        }


        [self.tablereloadData];

    }failure:^(NSURLSessionDataTask*_Nullabletask,NSError*_Nonnullerror) {

        NSLog(@"%@",error);


    }];

}

-(CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath{

    return 60;

}

-(void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath {


    Model*mod =self.data[indexPath.row];

   [[DataModel sharedDataHandle] addOneMovie:mod];

    NSLog(@"添加了第%d行的数据",indexPath.row);


}

- (IBAction)gotoxq:(id)sender {

    xqViewController*xq=[xqViewController new];

    [self.navigationController pushViewController:xq animated:YES];

}

@end





//

//  xqViewController.h

//  靠前瞎鸡儿信1

//

//  Created by 徐才茵 on 20/12/2018.

//  Copyright © 2018 徐才茵. All rights reserved.

//

#import

NS_ASSUME_NONNULL_BEGIN

@interfacexqViewController :UIViewController

@end

NS_ASSUME_NONNULL_END






//

//  xqViewController.m

//  靠前瞎鸡儿信1

//

//  Created by 徐才茵 on 20/12/2018.

//  Copyright © 2018 徐才茵. All rights reserved.

//

#import "xqViewController.h"

#import "DataModel.h"

#import "Model.h"

#import "UIImageView+WebCache.h"

@interface xqViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)UITableView*table;

@property(nonatomic,strong)NSMutableArray*array;

@end

@implementationxqViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    _table=[[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];

    _table.delegate=self;

    _table.dataSource=self;

    [self.view addSubview:_table];


    _array = [[DataModel sharedDataHandle] getAllMovies];

    [_table reloadData];

}

-(NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section{

    return_array.count;

}

-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{

    staticNSString*oj=@"cell";

    UITableViewCell*cell=[tableView dequeueReusableCellWithIdentifier:oj];

    if(!cell) {

        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:oj];

    }


    Model*s  = [_arrayobjectAtIndex:indexPath.row];

    cell.textLabel.text= s.title;

    [cell.imageViewsd_setImageWithURL:[NSURLURLWithString:s.imgsrc]];

    returncell;

}

-(BOOL)tableView:(UITableView*)tableView canEditRowAtIndexPath:(NSIndexPath*)indexPath {

    return YES;

}

-(void)tableView:(UITableView*)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath*)indexPath {


    Model*mod =self.array[indexPath.row];

    [[DataModel sharedDataHandle] deleteMovieByID:mod.ID];


    _array = [[DataModel sharedDataHandle] getAllMovies];

    [_table reloadData];


}

@end

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 用cocoaPods配置第三方文件 第一步。打开终端 第二步。cd+文件夹 第三步。pod init 第四步。打开...
    不说谎的匹诺曹Y阅读 1,355评论 0赞 1
  • 哦吼吼,又研究了几天,把FMDB这个封装好的数据库搞定了,写了个简单的例子,基于FMDB的添删改查操作,界面很一般...
    lichengjin阅读 733评论 0赞 0
  • 作者唯一QQ:228544117。。。。。 =========后面的都要新建一个文章 AppDelegate.h ...
    CC_iOS阅读 1,245评论 0赞 0
  • //联系人:石虎QQ: 1224614774昵称:嗡嘛呢叭咪哄 /**注意点: 1.看 GIF 效果图.2.看连线...
    石虎132阅读 819评论 0赞 12
  • 转载别人的文章 //联系人:石虎QQ: 1224614774昵称:嗡嘛呢叭咪哄 /** 注意点: 1.看 GIF ...
    Whatever永不放弃阅读 1,045评论 0赞 0

友情链接更多精彩内容