Anyone has sample code to show how to sort a NSDictionary (keys/values).
I can get the keys and values out in two separate NSArrays but how can I sort both simultaneously.
You can't really. What are you actually trying to accomplish with the keys and values?
You can get the keys as an array and sort it. Then iterate over the sorted key array and use each key to get the value from the original dictionary. But I don't know if that solves what you are trying to do.
You can't really. What are you actually trying to accomplish with the keys and values?
You can get the keys as an array and sort it. Then iterate over the sorted key array and use each key to get the value from the original dictionary. But I don't know if that solves what you are trying to do.
Here is the whole story:
1. I retrieve elements from my SQLITE database sorted and place these elements in a array of objects. All good here.
2. I then traverse the array using an NSEnumerator
Right here I realized I lost the sorting I got from the database. Somehow the Enumerator sorts by default on when the objects were created.
So now I'm trying to resort the array because I dont want to pay for going to the database.
So, my real question is how can I traverse the array without loosing the order.
If the items were already sorted as you added each item to the array then they are still ordered in the array (and why did you ask about dictionaries?).
Just do this:
Code:
// someSortedArray is your array with the sorted data from the database
// Replace 'MyObject' with whatever is really in your array
for (MyObject *obj in someSortedArray) {
// Do something with 'obj'
}
1. I retrieve elements from my SQLITE database sorted and place these elements in a array of objects. All good here.
2. I then traverse the array using an NSEnumerator
Right here I realized I lost the sorting I got from the database. Somehow the Enumerator sorts by default on when the objects were created.
So now I'm trying to resort the array because I dont want to pay for going to the database.
So, my real question is how can I traverse the array without loosing the order.
You can traverse an NSArray using plain-old 0 through (n-1) indexing. Search the docs. Assuming your entries are added to the array pre-sorted, they should remain sorted while in the array.
If the items were already sorted as you added each item to the array then they are still ordered in the array (and why did you ask about dictionaries?).
Just do this:
Code:
// someSortedArray is your array with the sorted data from the database
// Replace 'MyObject' with whatever is really in your array
for (MyObject *obj in someSortedArray) {
// Do something with 'obj'
}
So why people use Enumerators for, if you can traverse the Array this way?
Thanks this will solved my problem. I had created a dictionary of a couple of elements (i'm retrieving many from the DB) as I was traversing the array to display in another view and I was loosing the sort.