swift 2 时日的 coredata 增加和删除改查

写那些是对coredata那些放手的数据库的一个总括

简述:Cocoa框架中的NSPredicate用于查询,原理和用法都类似于SQL中的where,作用也就是数据库的过滤取。

简述:Cocoa框架中的NSPredicate用于查询,原理和用法都好像于SQL中的where,功效相当于数据库的过滤取。

谓词(NSPredicate)

OC中的谓词操作是本着于数组类型的,他就好比数据库中的查询操作,数据源正是数组,那样的利润是大家没有须求编写制定比相当多代码就足以去操作数组,同一时间也起到过滤的法力,大家能够编写轻巧的谓词语句,就足以从数组中过滤出大家想要的数据。非常有助于。在Java中是未曾这种技术的,可是有开源的框架已经达成了此功用。

下边看现实的例子。
Person.h

#import <Foundation/Foundation.h>

@interface Person : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger age;

+(id)personWithName:(NSString *)name andAge:(NSInteger)age;

@end

Person.m

#import "Person.h"

@implementation Person

+(id)personWithName:(NSString *)name andAge:(NSInteger)age
{
    Person *person = [[Person alloc]init];
    person.name = name;
    person.age = age;
    return person;
}

-(NSString *)description
{
    NSString *s = [NSString stringWithFormat:@"name=%@,age=%ld", _name, _age];
    return s;
}

@end

上面看一下回顾的用法

#import "ViewController.h"
#import "Person.h"

@interface ViewController ()

@property (nonatomic, strong) NSArray *persons;

@end

@implementation ViewController

- (NSArray *)persons
{
    if (_persons == nil) {
        self.persons = [NSArray arrayWithObjects:
                        [Person personWithName:@"mac" andAge:20],
                        [Person personWithName:@"1" andAge:30],
                        [Person personWithName:@"2" andAge:40],
                        [Person personWithName:@"3" andAge:50],
                        [Person personWithName:@"4" andAge:60],
                        [Person personWithName:@"5" andAge:70],
                        [Person personWithName:@"6" andAge:20],
                        [Person personWithName:@"7" andAge:40],
                        [Person personWithName:@"8" andAge:60],
                        [Person personWithName:@"9" andAge:40],
                        [Person personWithName:@"我" andAge:80],
                        [Person personWithName:@"10" andAge:90],
                        [Person personWithName:@"1" andAge:20], nil];
    }
    return _persons;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age < %d", 30];
    // 查询name=1的并且age大于40
    predicate = [NSPredicate predicateWithFormat:@"name = '1' && age < %d", 40];

    // in 包含
    predicate = [NSPredicate predicateWithFormat:@"self.name IN {'1','2','4'} || self.age IN {30,40}"];

    // name 以m开头
    predicate = [NSPredicate predicateWithFormat:@"name BEGINSWITH 'm'"];

    // name 以c结尾
    predicate = [NSPredicate predicateWithFormat:@"name ENDSWITH 'a'"];

    // name 包含
    predicate = [NSPredicate predicateWithFormat:@"name CONTAINS '我'"];

    // like 匹配任意多个字符
    // name中只要有s字符就能满足条件
    predicate = [NSPredicate predicateWithFormat:@"name like '*我*'"];

    // ? 代表一个字符,*代表任意多个字符。下面的查询条件是:name中第二个字符是a,name有2个字符
    predicate = [NSPredicate predicateWithFormat:@"name like '?a'"];

    // name中第二个字符是a, name有任意多个字符
    predicate = [NSPredicate predicateWithFormat:@"name like '?a'"];


    NSArray *array = [self.persons filteredArrayUsingPredicate:predicate];


    NSLog(@"filterArray=%@", array);

}

@end

私下认可读者已经对 coredata 有了基本理解,并未有涉嫌 relationships
等高级功效,只是对coredata的每一样基本操作做个计算

概念(最常用到的议程):

概念(最常用到的不二等秘书技):

NSPredicate 中的运算符

从地方的事例中大家看来,创设谓词使用类方法predicateWithFormat:
(NSString*) format,format 里的事物确实和SQL 的where
条件相仿。别的,参数format 与NSLog
的格式化模版类似。别的谓词能够包容正则使用,功效庞大。

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

  2. 逻辑运算符:AND、OENCORE、NOT 那多少个运算符总括并、或、非的结果。

  3. 限定运算符:IN 、BETWEEN
    例:@”number BETWEEN {1,5}”
    @”address IN {‘shanghai’,’nanjing’}”

  4. 字符串本人:SELF
    例:@”SELF == ‘APPLE'”

  5. 字符串相关:BEGINSWITH、ENDSWITH、CONTAINS
    例: @”name CONTAINS[cd] ‘ang'” //包含有些字符串
    @”name BEGINSWITH[c] ‘sh'” //以某些字符串伊始
    @”name ENDSWITH[d] ‘ang'” //以某些字符串甘休
    注:[c]不区分轻重缓急写 , [d]不区分发音符号即未有重音符号 ,
    [cd]既不区分轻重缓急写,也不区分发音符号。

  6. 通配符:LIKE
    例:@”name LIKE[cd] ‘er‘” //代表通配符,Like也经受[cd].
    @”name LIKE[cd] ‘???er
    ‘”

  7. 正则表达式:MATCHES
    例:NSString *regex = @”^A.+e$”; //以A开头,e结尾
    @”name MATCHES %@”,regex

经过那几个轻易的指令,可以让你一点也不慢做好一个数据库的操作,轻易营造 todo
或记事本等急需操作本地数据库的 app

1 NSPredicate *ca = [NSPredicate predicateWithFormat:(NSString *), ...]; 
NSPredicate *ca = [NSPredicate predicateWithFormat:(NSString *), ...]; 

动用NSPredicate在七个数组之间进行差距筛选

NSArray* array = @[@"aa",@"bb"];
NSArray* array2 = @[@"aa",@"bb",@"cc",@"dd"];
NSPredicate* thePredicate = [NSPredicate predicateWithFormat:@"NOT(SELF in %@)",array];
NSArray* arr3 = [array2 filteredArrayUsingPredicate:thePredicate];
NSLog(@"%@",arr3);

// 输出结果
arr3={@"cc" ,@"dd"}

一,盘算干活1,成立项指标时候,勾选“**Use Core Data**”。实现后在
**AppDelegate** 中,会转移相关代码。

Format:
(1)相比运算符>,<,==,>=,<=,!=
可用于数值及字符串
例:@”number > 100″

Format:

  • (1)相比运算符>,<,==,>=,<=,!=可用于数值及字符串
    例:@”number > 100″

  • (2)范围运算符:IN、BETWEEN
    例:@”number BETWEEN {1,5}”
    @”address IN {‘shanghai’,’beijing’}”

  • (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] ‘er‘”
    //**代表通配符,Like也承受[cd].
    @”name LIKE[cd] ‘???er
    ‘”

  • (6)正则表明式:MATCHES
    例:NSString *regex = @”^A.+e$”; //以A开头,e结尾
    @”name MATCHES %@”,regex

选用正则筛选三个数组

NSString *regex = @"^A.+e$";//以A 开头,以e 结尾的字符。
NSPredicate *pre= [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
if([pre evaluateWithObject: @"Apple"]){
    printf("YES\n");
}else{
    printf("NO\n");
}

只要想在已某个项目中新集成 coredata 请参考这里

(2)范围运算符:IN、BETWEEN
例:@”number BETWEEN {1,5}”
      @”address IN {‘shanghai’,’beijing’}”

实在使用:

(1)对NSArray举办过滤

NSArray *array = [[NSArray alloc]initWithObjects:@"beijing",@"shanghai",@"guangzou",@"wuhan", nil];    
NSString *string = @"ang";    
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF CONTAINS %@",string];    
NSLog(@"%@",[array filteredArrayUsingPredicate:pred]);

(2)判定字符串首字母是不是为字母:

NSString *regex = @"[A-Za-z]+";    
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];      
if ([predicate evaluateWithObject:aString]) {  

}  

(3)字符串替换:

NSError* error = NULL;    
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:@"(encoding=\")[^\"]+(\")"    
                                                                        options:0    
                                                                        error:&error];    
NSString* sample = @"<xml encoding=\"abc\"></xml><xml encoding=\"def\"></xml><xml encoding=\"ttt\"></xml>";    
NSLog(@"Start:%@",sample);    
NSString* result = [regex stringByReplacingMatchesInString:sample    
                                                  options:0    
                                                   range:NSMakeRange(0, sample.length)    
                                                  withTemplate:@"$1utf-8$2"];    
NSLog(@"Result:%@", result);

(4)截取字符串如下:

//组装一个字符串,需要把里面的网址解析出来    
NSString *urlString=@"<meta/><link/><title>1Q84 BOOK1</title></head><body>";    

//NSRegularExpression类里面调用表达的方法需要传递一个NSError的参数。下面定义一个      
NSError *error;    

//http+:[^\\s]* 这个表达式是检测一个网址的。(?<=title\>).*(?=</title)截取html文章中的<title></title>中内文字的正则表达式    
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(?<=title\\>).*(?=</title)" options:0 error:&error];    

if (regex != nil) {    
NSTextCheckingResult *firstMatch=[regex firstMatchInString:urlString options:0 range:NSMakeRange(0, [urlString length])];    

    if (firstMatch) {    
        NSRange resultRange = [firstMatch rangeAtIndex:0];    

        //从urlString当中截取数据    
        NSString *result=[urlString substringWithRange:resultRange];    
        //输出结果    
        NSLog(@"->%@<-",result);    
    }    
}

(5)剖断手提式有线电话机号码,电话号码函数

// 正则判断手机号码地址格式  
- (BOOL)isMobileNumber:(NSString *)mobileNum  
{  
   /** 
    * 手机号码 
    * 移动:134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188 
    * 联通:130,131,132,152,155,156,185,186 
    * 电信:133,1349,153,180,189 
    */  
   NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";  
   /** 
    10         * 中国移动:China Mobile 
    11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188 
    12         */  
   NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";  
   /** 
    15         * 中国联通:China Unicom 
    16         * 130,131,132,152,155,156,185,186 
    17         */  
   NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";  
   /** 
    20         * 中国电信:China Telecom 
    21         * 133,1349,153,180,189 
    22         */  
   NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";  
   /** 
    25         * 大陆地区固话及小灵通 
    26         * 区号:010,020,021,022,023,024,025,027,028,029 
    27         * 号码:七位或八位 
    28         */  
  // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";  

   NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];  
   NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];  
   NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];  
   NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];  

    if (([regextestmobile evaluateWithObject:mobileNum] == YES)  || ([regextestcm evaluateWithObject:mobileNum] == YES)|| ([regextestct evaluateWithObject:mobileNum] == YES)   || ([regextestcu evaluateWithObject:mobileNum] == YES)) {  
        if([regextestcm evaluateWithObject:mobileNum] == YES) {  
            NSLog(@"China Mobile");  
        } else if([regextestct evaluateWithObject:mobileNum] == YES) {  
            NSLog(@"China Telecom");  
        } else if ([regextestcu evaluateWithObject:mobileNum] == YES) {  
            NSLog(@"China Unicom");  
        } else {  
            NSLog(@"Unknow");  
        }  

      return YES;  

     }  else   {  

      return NO;  
  }  
} 

(6)邮箱验证、电话号码验证:

//是否是有效的正则表达式  

+(BOOL)isValidateRegularExpression:(NSString *)strDestination byExpression:(NSString *)strExpression  {  

   NSPredicate *predicate = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@", strExpression];    

   return [predicate evaluateWithObject:strDestination];  

}  

//验证email  
+(BOOL)isValidateEmail:(NSString *)email {  

   NSString *strRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{1,5}";  

   BOOL rt = [CommonTools isValidateRegularExpression:email byExpression:strRegex];  

   return rt;  

}  

//验证电话号码  
+(BOOL)isValidateTelNumber:(NSString *)number {  

   NSString *strRegex = @"[0-9]{1,20}";  

   BOOL rt = [CommonTools isValidateRegularExpression:number byExpression:strRegex];  

   return rt;  

} 

(7)NSDate进行筛选

//日期在十天之内:  
NSDate *endDate = [[NSDate date] retain];  
NSTimeInterval timeInterval= [endDate timeIntervalSinceReferenceDate];  
timeInterval -=3600*24*10;  
NSDate *beginDate = [[NSDate dateWithTimeIntervalSinceReferenceDate:timeInterval] retain];  
//对coredata进行筛选(假设有fetchRequest)  
NSPredicate *predicate_date = [NSPredicate predicateWithFormat:@"date >= %@ AND date <= %@", beginDate,endDate];  

[fetchRequest setPredicate:predicate_date];  
//释放retained的对象  
[endDate release];  
[beginDate release];

转自:http://blog.csdn.net/lianbaixue/article/details/10579117

2,展开项目中的 xcdatamodeld
文件,在侧面的数据模型编辑器的最底层工具栏点击 Add Entity
增多实体。同一时候在属性栏中对实业命名举行改变,并在 **Attribute**
栏目中增加 **userIDuserNameuserImage**
三个性格用以存款和储蓄顾客基本资料。

(3)字符串本身:SELF 
例:@“SELF == ‘APPLE’”

图片 1Paste_Image.png

(4)字符串相关:BEGINSWITH、ENDSWITH、CONTAINS
例:@”name CONTAIN[cd] ‘ang'”   //包蕴有个别字符串
       @”name BEGINSWITH[c] ‘sh'”     //以某些字符串初始
       @”name ENDSWITH[d] ‘ang'”      //以有些字符串甘休
       
注:[c]不区分轻重缓急写[d]不区分发音符号即未有重音符号[cd]既不区分轻重缓急写,也不区分发音符号。

相关文章