Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
860 views
in Technique[技术] by (71.8m points)

cocoa - How do I sort a swift array containing instances of NSManagedObject subclass by an attribute value (date)

I'm trying to sort an array as laid out in the accepted answer to this question, but am running into the problem which Isuru mentions in the comments on that answer. Namely, the code which should sort the array by the entity's "date" attribute brings the compiler complaint "could not find member 'date'"

Here is the NSManagedObject subclass describing the entity:

import Foundation
import CoreData

@objc(Entry)
class Entry: NSManagedObject {

    @NSManaged var date: NSDate
    @NSManaged var reflections: AnyObject
    @NSManaged var contactComment: NSSet
    @NSManaged var person: NSSet

    override func awakeFromInsert() {
        let now:NSDate = NSDate()
        self.date = now;
    }
}

And here is the code which tries to sort the array:

lazy var entries:[Entry] = {
    var days:[Entry] = self.managedObjectContext!.requestEntity("Entry")as [Entry]
    days.sort({$0.date < $1.date})

    var today:Entry = days.last!
    println(today.date)
    return days
}()

Note that in the latter part of that code, I am able to access and log the "date" property for one of the entries, and the Compiler doesn't have a problem with it.

Is my syntax for sorting correct? Is there another issue with this code I'm not seeing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is partly an issue with the Swift compiler not giving you a helpful error. The real issue is that NSDate can't be compared with < directly. Instead, you can use NSDate's compare method, like so:

days.sort({ $0.date.compare($1.date) == NSComparisonResult.OrderedAscending })

Alternatively, you could extend NSDate to implement the Comparable protocol so that it can be compared with < (and <=, >, >=, ==):

public func <(a: NSDate, b: NSDate) -> Bool {
    return a.compare(b) == NSComparisonResult.OrderedAscending
}

public func ==(a: NSDate, b: NSDate) -> Bool {
    return a.compare(b) == NSComparisonResult.OrderedSame
}

extension NSDate: Comparable { }

Note: You only need to implement < and == and shown above, then rest of the operators <=, >, etc. will be provided by the standard library.

With that in place, your original sort function should work just fine:

days.sort({ $0.date < $1.date })

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...