• CoreData


    插入:

    - (void)insertCoreData2
    {
        NSManagedObjectContext *context = [self managedObjectContext];
        Orange *orange = [NSEntityDescription insertNewObjectForEntityForName:@"Orange" inManagedObjectContext:context];
        
        orange.color = @"org";
        NSError *error;
        BOOL b = [context save:&error];
        NSLog(@"%@",b?@"YES":@"NO");
    }

     查询:

    - (void)getByQuery
    {
        NSManagedObjectContext *context = [self managedObjectContext];
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        [fetchRequest setEntity:[NSEntityDescription entityForName:@"Orange" inManagedObjectContext:context]];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"color like[cd]'red'"];
        [fetchRequest setPredicate:predicate];
        [fetchRequest setFetchBatchSize:5];
        [fetchRequest setFetchOffset:0];
        [fetchRequest setFetchLimit:5];
        NSSortDescriptor *sortDesc = [[NSSortDescriptor alloc] initWithKey:@"color" ascending:YES];
        NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDesc, nil];
        [fetchRequest setSortDescriptors:sortDescriptors];
        NSError *error;
        NSArray *fetchedItems = [context executeFetchRequest:fetchRequest error:&error];
        if (fetchRequest == nil) {
            NSLog(@"fetch request resulted in an error: %@,%@ ", error, [error userInfo]);
        }
        for (Orange *orange in fetchedItems) {
            NSLog(@"%@", orange.color);
        }
    }

     更新:

     NSFetchRequest* request=[[NSFetchRequest alloc] init];  
        NSEntityDescription* user=[NSEntityDescription entityForName:@"User" inManagedObjectContext:_myAppDelegate.managedObjectContext];  
        [request setEntity:user];  
        //查询条件  
        NSPredicate* predicate=[NSPredicate predicateWithFormat:@"name==%@",@"chen"];  
        [request setPredicate:predicate];  
        NSError* error=nil;  
        NSMutableArray* mutableFetchResult=[[_myAppDelegate.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];  
        if (mutableFetchResult==nil) {  
            NSLog(@"Error:%@",error);  
        }  
        NSLog(@"The count of entry: %i",[mutableFetchResult count]);  
        //更新age后要进行保存,否则没更新  
        for (User* user in mutableFetchResult) {  
            [user setAge:[NSNumber numberWithInt:12]];  
              
        }  
        [_myAppDelegate.managedObjectContext save:&error];  
        [mutableFetchResult release];  
        [request release]; 
  • 相关阅读:
    判断以下字符串中出现次数最多的字符,并且算出该字符出现的次数
    status的状态码
    call和apply的区别?
    闭包
    $(document).ready和window. onload的区别
    python_pandas常用操作
    python经典例题
    爬B站并保存成csv文件。提供数据
    data_analysis:初识numpy
    01爬取豆瓣网电影数据进行numpy的练习
  • 原文地址:https://www.cnblogs.com/apem/p/4349524.html
Copyright © 2020-2023  润新知