onFormat string For NSPredicate

别说谁变了你拦得住时间么 提交于 2019-12-31 05:24:08

问题


I want to sort data with "id" key, how can I understand what is format string for NSPredicate format ? I have an 100 number post. My code :

 let objectIDs = posts.map{$0.id}
    let predicate = NSPredicate(format: "self IN %@", objectIDs)
    let sortByUserId = NSSortDescriptor(key: "id", ascending: true)

I have an error with this description:

can not parse "self IN %@" format string.

Code for Parsing JSON Data:

func postsFromJSONData(data : NSData, inContext context: NSManagedObjectContext) -> PostResult {
            do{
            let jsonObject : [[String:AnyObject]]
            = try NSJSONSerialization.JSONObjectWithData(data, options: []) as! [[String:AnyObject]]

            for postJSON in jsonObject {
                if let post = postFromJsonObject(postJSON, incontext : context) {

                        finalPost.append(post)
                    }
                }

            return .Sucsess(finalPost)
            }
            catch let error {
                return .Failure(error)
            }

        }

fetch the main queue posts when the web service finishes:

func fetchRecentPost(completion completion: (PostResult) -> Void){

    let request = NSURLRequest(URL: recentPostURL(["":""]))

let task = session.dataTaskWithRequest(request, completionHandler: {
    (data, response, error)  in

    var result = self.processRecentPostRequest(data: data, error: error)

    if case let .Sucsess(posts) = result {

        let mainQueueContext = self.coreDataStack.mainQueueContext
        mainQueueContext.performBlockAndWait(){

            try! mainQueueContext.obtainPermanentIDsForObjects(posts)
        }

        let objectIDs = posts.map{$0.id}
        let predicate = NSPredicate(format: "self IN %@", objectIDs)
        let sortByUserId = NSSortDescriptor(key: "id", ascending: true)

        do{
            try self.coreDataStack.saveChanges()
            let mainQueuePosts = try self.fetchMainQueuePosts(predicate: predicate, sortDiscriptors: [sortByUserId])
            result = .Sucsess(mainQueuePosts)
        }
        catch let error {

            result = .Failure(error)
        }
    }

        completion(result)

        })

回答1:


Your predicte should be like this

let predicate = NSPredicate(format: "id IN %@", objectIDs)
let sortByUserId = NSSortDescriptor(key: "id", ascending: true)

Note : It is either self.id IN %@ or id IN %@.



来源:https://stackoverflow.com/questions/39546321/onformat-string-for-nspredicate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!