2015-08-25 87 views
16

我有一個自定義對象「會議」我正在添加數組中的所有對象。我想要做的是從Meeting.meetingDate中排序數組。按日期排序自定義對象數組swift

我也使用解析,我有兩個查詢,並把結果放入一個數組。

我可以將數據添加到「meetingData」,但不能對其進行排序。

任何人都可以幫忙嗎?

所以我的數組是:

var meetingsData = [Meeting]() 

會議類:

public class Meeting: PFObject, PFSubclassing 
{ 

    @NSManaged public var meetingTitle: String? 
    @NSManaged public var meetingLocation: String? 
    @NSManaged public var meetingNotes: String? 
    @NSManaged public var meetingDuration: String? 
    @NSManaged public var createdBy: User? 
    @NSManaged public var meetingTime: NSDate? 
    @NSManaged public var meetingDate: NSDate? 

} 

數組的內容就像這樣:

<Meeting: 0x125edd040, objectId: xIqx7MoRd6, localId: (null)> { 
createdBy = "<PFUser: 0x125d627c0, objectId: RKCWJRj84O>"; 
meetingDate = "2015-08-29 17:07:12 +0000"; 
meetingDuration = "2 hours 2 mins"; 
meetingLocation = 4th Floor; 
meetingNotes = With Investors; 
meetingTime = "2015-08-24 09:00:17 +0000"; 
meetingTitle = Meeting with Investors; 
} 
<Meeting: 0x125ed95f0, objectId: tz4xx5p9jB, localId: (null)> { 
createdBy = "<PFUser: 0x125d627c0, objectId: RKCWJRj84O>"; 
meetingDate = "2015-08-23 23:00:00 +0000"; 
meetingDuration = "1 hour"; 
meetingLocation = "Emirates Stadium, London"; 
meetingNotes = "Football"; 
meetingTime = "2000-01-01 20:00:00 +0000"; 
meetingTitle = "Liverpool V Arsenal"; 
} 
<Meeting: 0x125ed95f0, objectId: tz4xx5p9jB, localId: (null)> { 
createdBy = "<PFUser: 0x125d627c0, objectId: RKCWJRj84O>"; 
meetingDate = "2015-09-23 23:00:00 +0000"; 
meetingDuration = "1 hour"; 
meetingLocation = "Library"; 
meetingNotes = "Dev Team"; 
meetingTime = "2000-01-01 10:00:00 +0000"; 
meetingTitle = "Code Review"; 
} 

我試圖做到這一點Swift how to sort array of custom objects by property value但它不起作用

在此先感謝

回答

42

NSDate不能與<直接比較。您可以在下面的代碼中使用的NSDatecompare方法,如:

meetingsData.sort({ $0.meetingDate.compare($1.meetingDate) == .OrderedAscending }) 

在上面的代碼,你可以更改使用NSComparisonResult枚舉排序的順序,在斯威夫特像下面這樣實現的:

enum NSComparisonResult : Int { 
    case OrderedAscending 
    case OrderedSame 
    case OrderedDescending 
} 

我希望這對你有所幫助。

+0

謝謝..我'使用'sortInPlace'的可變性 – jose920405

15

對於夫特3

meetingsData.sort(by: { $0.meetingDate.compare($1.meetingDate) == .orderedAscending}) 

OR

作爲日期現在在夫特3直接可比的,例如。

let firstDate = Date() 
    let secondDate = Date() 

    if firstDate < secondDate {  
    } else if firstDate == secondDate {   
    } else if firstDate > secondDate {   
    } 
+0

謝謝,Ramkrishna。看起來語法已經更新了一些,因爲你的帖子... meetingsData.sorted(通過:{$ 0.meetingDate.compare($ 1.meetingDate)== .orderedAscending}) – rockiesGrizzly