CoreData

//

//  ViewController.m

//  UI-NO-42-1 CoreData-1

//

//  Created by 容伟 on 15/10/5.

//  Copyright (c) 2015年 容伟. All rights reserved.

//

/*

 -------------------------------------------------------------

 CoreData:不需要编写任何SQL语句,直接存取对象;与关系型数据库相比如图:

 在CoreData里面  存储的都是NSManagerObject具体的对象

 CoreData负责管理这些对象之间的关系

 只要Xcode里面建立了visual map 就可以新建对象

 并把对象添加到数据库里面,同时也可以删除、查询

 modle里面包含了实体entity,相当于属性(没写完)

 

 注意:“实体”的名字首字母必须是大写,否则报错 !!!!

-------------------------------------------------------------

 操作coreData

 1、不管增删改查都需要先初始化 上下文[app managedObjectContext]

 2、插入具体内容到上下文

 + (id)insertNewObjectForEntityForName:(NSString *)entityName inManagedObjectContext:(NSManagedObjectContext *)context;

 3、保存 saveContext

 -------------------------------------------------------------

 谓词NSPredicate 条件语句

 1、比较运算符>,<,==,>=,<=,!=

 可用于数值和字符串等的比较

 如:@“age >= 23”  筛选 年纪大于23岁的元素

 

 2、范围运算符:IN、BETWEEN

 例:@"number BETWEEN {10,50}"

 @"address IN {'河南','北京'}"

 

 3、字符串本身:SELF

 例:@“SELF == ‘APPLE’"

 

 4、字符串相关:BEGINSWITH、ENDSWITH、CONTAINS

 例:@"name CONTAIN[cd] 'ang'"   //包含某个字符串

 @"name BEGINSWITH[c] 'sh'"     //以某个字符串开头

 @"name ENDSWITH[d] 'ang'"      //以某个字符串结束

 注:[c]不区分大小写[d]不区分发音符号即没有重音符号[cd]既不区分大小写,也不区分发音符号。

 

 (5)通配符:

 LIKE 模糊查询

 例:@"name LIKE[cd] '*b*'"    *代表通配符,表示前面后面 有一个或多个字符

 6、 正则表达式

 -------------------------------------------------------------

 读取coreData

 1、读取managedObjectModel

 2、找到里面所有实体的名字[model entitiesByName]

 3、找到要读取的实体NSEntityDescription *entry = entryDic[@"UserInfo"];

 4、初始化 查询对象 NSFetchRequest *request = [[NSFetchRequest alloc]init];

 5、通过上下文 查找 NSArray *list = [context executeFetchRequest:request error:nil];

 -------------------------------------------------------------

 */

 

#import "ViewController.h"

#import "AppDelegate.h"

 

#import "PostView.h"

 

#import "Message.h"

#import "UserInfo.h"

 

@interface ViewController ()<UITableViewDataSource, UITableViewDelegate>

{

    UITableView *showView;

    PostView *postView;   // 发布界面

    NSArray *dataList;

}

@end

 

@implementation ViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

    self.edgesForExtendedLayout = UIRectEdgeNone;

    self.navigationController.navigationBar.translucent = NO;

    self.tabBarController.tabBar.translucent = NO;

 

    [self addRightButtonItem];

    [self addShowView];

    

    [self loadData];

 

}

 

- (void)addRightButtonItem {

    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithTitle:@"Add" style:UIBarButtonItemStylePlain target:self action:@selector(createPostView)];

    self.navigationItem.rightBarButtonItem = right;

}

 

// 发布界面

- (void)createPostView {

    if (postView) {

        self.navigationItem.rightBarButtonItem.title = @"Add";

        [self done];

        [postView removeFromSuperview];

        postView = nil;

        return;

    }

    self.navigationItem.rightBarButtonItem.title = @"Done";

    postView = [[PostView alloc] initWithFrame:

    [UIScreen mainScreen].bounds];

    [self.view addSubview:postView];

    

}

 

- (void)done {

    [postView.titleTextField resignFirstResponder];

    [postView.contentTextField resignFirstResponder];

 

//    如果输入了内容 就将之保存到数据库

    if (postView.titleTextField.text.length!=0 && postView.contentTextField.text!=0) {

        

        [self addEntity];

        

    }else{

//        没有输入内容

    }

//    [showView reloadData];

 

 

    

}

 

- (void)addEntity {

//    操作coreData

//    1、不管增删改查都需要先初始化 上下文[app managedObjectContext]

//    2、插入具体内容到上下文

//    + (id)insertNewObjectForEntityForName:(NSString *)entityName inManagedObjectContext:(NSManagedObjectContext *)context;

//    3、保存 saveContext

    

    

//    1、初始化上下文

   NSManagedObjectContext *context = [[AppDelegate appDelegate] managedObjectContext];

    

//    2、实体描述

    Message *message = [NSEntityDescription insertNewObjectForEntityForName:@"Message" inManagedObjectContext:context];

    [message setValue:postView.titleTextField.text forKey:@"title"];

    [message setValue:postView.contentTextField.text forKey:@"content"];

    

    NSArray *images = @[@"2", @"3", @"4"];

    

    int arc = arc4random()%images.count;

    UserInfo *info = [NSEntityDescription insertNewObjectForEntityForName:@"UserInfo" inManagedObjectContext:context];

    [info setValue:images[arc] forKey:@"name"];

    [info setValue:@(19+arc) forKey:@"age"];

    

    UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%@", images[arc]]];  //  将字符串 转换成 data 类型

    

    [info setValue:UIImagePNGRepresentation(image) forKey:@"headerImage"];

    [info setValue:message forKey:@"message"];

 

    

//    保存数据

    [[AppDelegate appDelegate] saveContext];

    [self loadData];

}

 

// 加载数据

- (void)loadData {

//    读取coreData

//    1、读取managedObjectModel

//    2、找到里面所有实体的名字[model entitiesByName]

//    3、找到要读取的实体NSEntityDescription *entry = entryDic[@"UserInfo"];

//    4、初始化 查询对象 NSFetchRequest *request = [[NSFetchRequest alloc]init];

//    5、通过上下文 查找 NSArray *list = [context executeFetchRequest:request error:nil];

//    

    

   NSManagedObjectContext *context = [[AppDelegate appDelegate] managedObjectContext];

    

//    1、读取managedObjectModel

    NSManagedObjectModel *model = [[AppDelegate appDelegate] managedObjectModel];

//    2、找到里面所有实体的名字[model entitiesByName];

    NSDictionary *entitiesDic = [model entitiesByName];

//    3、找到要读取的实体 NSEntityDescription *entry = entryDic[@"UserInfo"];

    NSEntityDescription *entity = entitiesDic[@"UserInfo"];

//    4、初始化 查询请求对象 NSFetchRequest

    NSFetchRequest *request = [[NSFetchRequest alloc] init];

    request.entity = entity;

//   5、通过上下文开始查询

    dataList = [context executeFetchRequest:request error:nil];

    NSLog(@"dataList is %@", dataList);

    if (dataList.count != 0) {

        [showView reloadData];

    }

}

 

 

 

// 列表内容

- (void)addShowView {

    showView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame)-64) style:UITableViewStylePlain];

    showView.delegate = self;

    showView.dataSource = self;

    [self.view addSubview:showView];

}

 

#pragma mark - tableView 代理方法

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

    return dataList.count;

}

 

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

    return 100;

}

 

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

    NSString *cellId = @"id";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];

    if (!cell) {

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellId];

    }

    UserInfo *info = dataList[indexPath.row];

    cell.imageView.image = [UIImage imageWithData:info.headerImage];

    cell.textLabel.text = info.name;

    

    Message *message = info.message;

    cell.detailTextLabel.text = message.title;

    

    return cell;

}

 

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

 

@end

/  PostView.h

//  UI-NO-42-1 CoreData-1

//

//  Created by  on 15/10/5.

//

#import <UIKit/UIKit.h>

@interface PostView : UIView

@property (nonatomic, retain)UITextField *titleTextField;

@property (nonatomic, retain)UITextView *contentTextField;

@end

//

//  PostView.m

//  UI-NO-42-1 CoreData-1

//

//  Created by 容伟 on 15/10/5.

//  Copyright (c) 2015年 容伟. All rights reserved.

//

#import "PostView.h"

@implementation PostView

- (instancetype)initWithFrame:(CGRect)frame {

    self = [super initWithFrame:frame];

    if (self) {

        self.backgroundColor = [UIColor brownColor];

        self.titleTextField = [[UITextField alloc] initWithFrame:CGRectMake(10, 100, CGRectGetWidth([UIScreen mainScreen].bounds)-20, 40)];

        self.titleTextField.placeholder = @"请输入标题,在下面输入框输入内容";

        self.titleTextField.borderStyle = UITextBorderStyleRoundedRect;

        [self addSubview:self.titleTextField];

        

        

        

        

        self.contentTextField = [[UITextView alloc] initWithFrame:CGRectMake(10, CGRectGetMaxY(self.titleTextField.frame)+10, CGRectGetWidth([UIScreen mainScreen].bounds)-20, 200)];

        self.contentTextField.layer.cornerRadius = 5;

        self.contentTextField.layer.borderColor = [UIColor grayColor].CGColor;

        self.contentTextField.layer.borderWidth = 1;

        [self addSubview:self.contentTextField];

    }

    return self;

}

@end

 

原文地址:https://www.cnblogs.com/wukun16/p/4884174.html