Stack108 Stack108 - 7 months ago 31
Swift Question

Swift reorder dynamic UITableView by NSDate

in my app with swift 2 programming language,i have a UITableView which will be fill with core date items.

As you can see in this post, i have already asked for a sorting function:
http://stackoverflow.com/a/36703648/6012187

func ReSort() {
CoreDataItems.sortInPlace({sortAscending ? $0.RowName < $1.RowName : $0.RowName > $1.RowName})
sortAscending = !sortAscending
tableView.reloadData()
}


Now my question is, how can i set dynamically the RowName Value?
for example. i save the the RowName in the user defaults.

but
$0.defaults.objectForKey("xx")
doesn't work without syntax error

Next question is:

How can i sort with a row, which value is a NSDate?

Thank you very much :)

Answer

You can sort NSArray which contains NSDate by using this code:

// objective-c code
NSSortDescriptor *dateDescriptor = [NSSortDescriptor
                             sortDescriptorWithKey:@"startDateTime" 
                                         ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:dateDescriptor];
NSArray *sortedEventArray = [nodeEventArray
 sortedArrayUsingDescriptors:sortDescriptors];

//swift code
let dateDescriptor :NSSortDescriptor = NSSortDescriptor(key: "startDateTime", ascending: true)
let sortdescriptors: NSArray = [dateDescriptor]
let sortedeventarray = nodeEventArray.sortedArrayUsingDescriptors([dateDescriptor])

After sorting is done, you can reload your tableview

Comments