CoreData限制相关实体批量大小

时间:2015-09-07 21:24:20

标签: ios swift sqlite core-data

我遇到了一个非常简单的CoreData问题,但似乎很难解决。编写一个简单的聊天应用程序,每个用户都有很多消息。

class CoreUser: NSManagedObject
{
    @NSManaged var firstname: String?
    @NSManaged var id: String?
    @NSManaged var lastname: String?
    @NSManaged var nickname: String?
    @NSManaged var messages: NSSet
}

class CoreMessage: NSManagedObject
{
    @NSManaged var body: String?
    @NSManaged var owner: CoreUser
    @NSManaged var state: String
    @NSManaged var timestamp: NSDate
}

关系是:一对多

获取用户实体:

func getCoreUser(userId: String) -> CoreUser?
{
    var error: NSError?;
    let fetchRequest = NSFetchRequest(entityName: "CoreUser");
    let nodeId = NSString(string: userId.lowercaseString);
    let pred = NSPredicate(format: "id == %@", nodeId);
    fetchRequest.fetchLimit = 1;
    fetchRequest.predicate = pred;
    let fetchResults = self.managedObjectContext!.executeFetchRequest(fetchRequest, error: &error) as? [CoreUser];

    if let results = fetchResults
    {
        return results.first;
    }
    return nil;
}

如何限制相关的消息实体(20条消息,按日期排序)。结果数组包含来自该用户的所有消息。

帮助你。

1 个答案:

答案 0 :(得分:6)

获取请求始终从托管对象上下文返回对象。你无法取得&#34;修改过的&#34;对象,例如带有&#34;限制&#34;的function listTracks($id) { $sql = "SELECT tkl.id, tkl.name, description, GROUP_CONCAT(DISTINCT tk.name SEPARATOR '<br />') trackslist FROM tracklists tkl LEFT OUTER JOIN tracks tk ON tk.tracklist_id=tkl.id WHERE tk.id=:id GROUP BY tkl.id ORDER BY tkl.id DESC"; $param = array(':id' => $id); $stmt = $pdo->prepare($sql); $stmt->execute($param); $result = $stmt->fetchAll(PDO::FETCH_ASSOC); $list = ""; foreach($result as $tracks => $track){ $list .= "<li>".$track['name']."</li> <li>".$track['description']."</li> <li>". $track['tracklist'] ."</li>"; } return $list; } 个对象与CoreUser的关系。

但你可以做的是获取相关的CoreMessage个对象 给定用户:

CoreMessage

现在您可以添加提取限制以限制检索的数量 消息:

let fetchRequest = NSFetchRequest(entityName: "CoreMessage")
fetchRequest.predicate = NSPredicate(format: "owner.id == %@", nodeId)

以及合适的排序描述符。