iOSDev
iOSDev

Reputation: 3617

get contents of nsdictionary into nsarray without changing order

I am using:

NSArray *values = [myDict allValues];

to get all contents of dictionary into an array, but it is changing the order of contents.

The contents are received from an url and are retrieved as follows:

NSDictionary *myDict = [[NSDictionary alloc] initWithContentsOfURL:url];    

I want the order of contents to be maintained. How do I do that?

Thanks

Upvotes: 0

Views: 1488

Answers (4)

Brad The App Guy
Brad The App Guy

Reputation: 16275

Unfortunately, NSDictionaries have no concept of an order. There is no guarantee that you will get objects back in the same order that you put them in.

You could (re)sort the objects after they are in an array using -[NSArray sortedArrayUsingSelector:]

Another option would be to use a differnet container other than NSDictionary that does guaraeentee order. Matt Gallagher has an eaxmpale of a class cluster to acoplish this on this blog: “OrderedDictionary: Subclassing a Cocoa class cluster”

Upvotes: 0

Dair
Dair

Reputation: 16240

You have to sort the NSArray after you store the values. I don't know how you want to sort the array but NSArray has a method like this:

[anArray sortedArrayUsingSelector:@selector(mySortFunc:)];

So you call this and then you make a custom sort function:

- (NSComparisonResult)mySortFunc:(Object *)otherObject {
    //Implement this to how you want to sort it.
    // return
}

Look here for more detail:

How to sort an NSMutableArray with custom objects in it?

Or alternatively: look at the comment I have made referring to how to make an ordered NSDictionary.

http://cocoawithlove.com/2008/12/ordereddictionary-subclassing-cocoa.html

Upvotes: 0

DRVic
DRVic

Reputation: 2481

The order of the keys in an NSDictionary is undefined

If you have a sorted order in which you would like them to appear in the array you can sort the array. If you're just looking for them to be in the same order as they were in the file, passing through an NSDictionary is going to make that impossible.

There is arrayWithContentsOfURL, but I don't know that will help you, as the file has to be in the right format.

Upvotes: 3

Phillip Mills
Phillip Mills

Reputation: 31016

A dictionary data structure doesn't really have an implicit ordering, just keys and values. If you have an ordering in mind that you can apply to the keys, you can get them in an array and then retrieve their matching values.

Upvotes: 1

Related Questions