https://developer.apple.com/library/content/documentation/DataManagement/Conceptual/CoreDataSnippets/Articles/fetching.html

This article contains snippets for fetching managed objects.

To fetch managed objects, you minimally need a managed object context against which to execute the fetch, and an entity description to specify the entity you want. You create an instance of NSFetchRequest and specify its entity. You may optionally specify an array of sort orderings and/or a predicate.

How you get the managed object context depends on your application architecture—see Getting a Managed Object Context. Once you have the context, though, you can get the entity using NSEntityDescription’s convenience method, entityForName:inManagedObjectContext:.

Basic Fetch

To get all the managed objects of a given entity, create a fetch request and specify just the entity:

NSManagedObjectContext *context = <#Get the context#>;
 
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"<#Entity name#>"
    inManagedObjectContext:context];
[fetchRequest setEntity:entity];
 
NSError *error;
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects == nil) {
    // Handle the error.
}

Fetch with Sorting

To fetch managed objects in a particular order, in addition to the components in the basic fetch (described in Basic Fetch) you need to specify an array of sort orderings:

NSManagedObjectContext *context = <#Get the context#>;
 
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"<#Entity name#>"
    inManagedObjectContext:context];
[fetchRequest setEntity:entity];
 
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"<#Sort key#>"
    ascending:YES];
NSArray *sortDescriptors = @[sortDescriptor];
[fetchRequest setSortDescriptors:sortDescriptors];
 
NSError *error;
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects == nil) {
    // Handle the error.
}

Fetch with a Predicate

To fetch managed objects that meet given criteria, in addition to the components in the basic fetch (described in Basic Fetch) you need to specify a predicate:

NSManagedObjectContext *context = <#Get the context#>;
 
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"<#Entity name#>"
    inManagedObjectContext:context];
[fetchRequest setEntity:entity];
 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"<#Predicate string#>",
    <#Predicate arguments#>];
[fetchRequest setPredicate:predicate];
 
NSError *error;
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects == nil) {
    // Handle the error.
}

For more about predicates, see Predicate Programming Guide. For an alternative technique for creating the predicate that may be more efficient, see Fetch with a Predicate Template.

Fetch with a Predicate Template

To fetch managed objects that meet given criteria, in addition to the components in the basic fetch (described in Basic Fetch) you need to specify a predicate.NSPredicate’s predicateWithFormat: method is typically the easiest way to use a predicate (as shown in Fetch with a Predicate), but it’s not the most efficient way to create the predicate itself. The predicate format string has to be parsed, arguments substituted, and so on. For performance-critical code, particularly if a given predicate is used repeatedly, you should consider other ways to create the predicate. For a predicate that you might use frequently, the easiest first step is to create a predicate template. You might create an accessor method that creates the predicate template lazily on demand:

// Assume an instance variable:
// NSPredicate *predicateTemplate;
 
- (NSPredicate *)predicateTemplate {
    if (predicateTemplate == nil) {
        predicateTemplate = [NSPredicate predicateWithFormat:@"<#Key#> <#Operator#> <#$Variable#>"];
    }
    return predicateTemplate;
}

When you need to use the template, you create a dictionary containing the substitution variables and generate the predicate using predicateWithSubstitutionVariables:.

NSManagedObjectContext *context = <#Get the context#>;
 
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"<#Entity name#>"
    inManagedObjectContext:context];
[fetchRequest setEntity:entity];
 
NSDictionary *variables = @{ @"<#Variable#>" : <#Value#> };
NSPredicate *predicate = [[self predicateTemplate]
    predicateWithSubstitutionVariables:variables];
[fetchRequest setPredicate:predicate];
 
NSError *error;
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects == nil) {
    // Handle the error.
}

For more about predicates, see Predicate Programming Guide.

Fetch with Sorting and a Predicate

To fetch managed objects that meet given criteria and in a particular order, in addition to the components in the basic fetch (described in Basic Fetch) you need to specify a predicate and an array of sort orderings.

NSManagedObjectContext *context = <#Get the context#>;
 
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"<#Entity name#>" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
 
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"<#Sort key#>" ascending:YES];
NSArray *sortDescriptors = @[sortDescriptor];
[fetchRequest setSortDescriptors:sortDescriptors];
 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"<#Predicate string#>",
    <#Predicate arguments#>];
[fetchRequest setPredicate:predicate];
 
NSError *error;
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects == nil) {
    // Handle the error.
}

For more about predicates, see

coreData-Fetching Managed Objects的更多相关文章

  1. iOS10 CoreData新特性

    原文地址:What's New in Core Data in macOS 10.12, iOS 10.0, tvOS 10.0, and watchOS 3.0 翻译者:肖品,原创文章转载请著名出处 ...

  2. iOS-数据持久化-CoreData

    CoreData详解 介绍: 在Cocoa环境下,如果你想使用数据库(如sqlite),你可以使用sql语句的方式通过相关的工具类进行数据库的直接操作.当然你也可以通过别人封装之后的一些简单框架,使得 ...

  3. iOS CoreData学习资料 和 问题

    这里是另一篇好文章 http://blog.csdn.net/kesalin/article/details/6739319 这里是另一篇 http://hxsdit.com/1622 (不一定能访问 ...

  4. iphone dev 入门实例4:CoreData入门

    The iPhone Core Data Example Application The application developed in this chapter will take the for ...

  5. iOS CoreData (1)

    下面开始学习一下CoreData. Core Data不是一个关系型数据库,也不是关系型数据库管理系统(RDBMS). Core Data 为数据变更管理.对象存储.对象读取恢复的功能提供了支持. 它 ...

  6. 使用CoreData [4]

    使用CoreData [4] 此片文章主要是分析如何对CoreData进行封装. 在开始之前,我们需要弄明白3个非常关键的类,以下翻译凑合着看看. NSManagedObjectContext An ...

  7. iOS应用开发之CoreData[转]

    我目前的理解,CoreData相当于一个综合的数据库管理库,它支持sqlite,二进制存储文件两种形式的数据存储.而CoreData提供了存储管理,包括查询.插入. 删除.更新.回滚.会话管理.锁管理 ...

  8. ios之coredata(一)

    下面开始学习一下CoreData. Core Data不是一个关系型数据库,也不是关系型数据库管理系统(RDBMS).Core Data 为数据变更管理.对象存储.对象读取恢复的功能提供了支持. 它可 ...

  9. ios CoreData NSManagedObject 生命周期

    用同样的检索条件从context检索出的对象是一个????所以 在主页的3个brand没法释放,在仅仅处理brand的时候???? 和 多个 context无关 我重写了NSManagedObject ...

随机推荐

  1. 在ubuntu下如何验证文件的MD5码 (转载)

    转自:http://blog.csdn.net/david_xtd/article/details/7641682 在windows下可以使用专用的工具软件如WinMD5等来查看文件的MD5码, 在u ...

  2. 洛谷P4239 【模板】多项式求逆(加强版)(多项式求逆)

    传送门 咱用的是拆系数\(FFT\)因为咱真的不会三模数\(NTT\)-- 简单来说就是把每一次多项式乘法都改成拆系数\(FFT\)就行了 如果您还不会多项式求逆的左转->这里 顺带一提,因为求 ...

  3. scrapy爬取数据的基本流程及url地址拼接

    说明:初学者,整理后方便能及时完善,冗余之处请多提建议,感谢!   了解内容: Scrapy :抓取数据的爬虫框架     异步与非阻塞的区别   异步:指的是整个过程,中间如果是非阻塞的,那就是异步 ...

  4. C 语言实例 - 阶乘

    C 语言实例 - 阶乘 一个正整数的阶乘(英语:factorial)是所有小于及等于该数的正整数的积,并且0的阶乘为1.自然数n的阶乘写作n!. n!=×××...×n.阶乘亦可以递归方式定义:!=, ...

  5. The database could not be exclusively locked to perform the operation(SQL Server 5030错误解决办法)(转)

    Microsoft SQL Server 5030错误解决办法 今天在使用SQL Server时,由于之前创建数据库忘记了设置Collocation,数据库中插入中文字符都是乱码,于是到DataBas ...

  6. openSUSE 跨版本升级

    准备工作 此方法通过网络跨版本升级,适合 Leap 升级到下一个发行版(如 42.2 升级到 42.3),也适合 Leap 升级为 Tumbleweed.首先必须确定升级的时候有足够的时间.靠谱的更新 ...

  7. Cent OS 6.5 下 Node.js安装

    打开官网 http://nodejs.org/ 点击那个绿色的INSTALL 按钮下载安装包,然后解压.   基本的环境我原本已经安装完毕,这是需求的环境,来源安装包中的README.md,需要的自行 ...

  8. Oracle .NET Core

    Oracle .NET Core Beta驱动已出,自己动手写EF Core Oracle https://www.cnblogs.com/yanweidie/p/9064609.html 使用.ne ...

  9. 关于AQS——独占锁的相关方法(一)

    一.序言 Lock接口是juc包下一个非常好用的锁,其方便和强大的功能让他成为synchronized的一个很好的替代品. 我们常用的一个Lock的实现类(好像也是唯一一个只实现了Lock接口的类) ...

  10. clickhouse源码Redhat系列机单机版安装踩坑笔记

    前情概要 由于工作需要用到clickhouse, 这里暂不介绍概念,应用场景,谷歌,百度一大把. 将安装过程踩下的坑记录下来备用 ClickHouse源码 git clone安装(直接下载源码包安装失 ...