Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

What's the purpose of orderedDictionaryWithDictionary: method? #4

Closed
zakdances opened this issue Sep 12, 2013 · 2 comments
Closed

What's the purpose of orderedDictionaryWithDictionary: method? #4

zakdances opened this issue Sep 12, 2013 · 2 comments

Comments

@zakdances
Copy link
Contributor

Passing in an NSDictionary (which is unordered) to initialize an ordered dictionary doesn't sound valid. Shouldn't this method be replaced by a orderedDictionaryWithObjectsAndKeys: method so that an ordered dictionary can be initialized with multiple ordered keys/values?

@Marxon13
Copy link
Owner

If you look at the code, orderedDictionaryWithContentsOfDictionary: runs this method to create the ordered dictionary:

- (id)initWithContentsOfDictionary:(NSDictionary *)entrys
{
    self = [super init];
    if (self != nil) {
        keys = [[NSMutableArray alloc] initWithArray:entrys.allKeys];
        objects = [[NSMutableArray alloc] init];
        //Must loop through all keys, since order from NSDictionary is not defined.
        for (id key in keys) {
            [objects addObject:[entrys objectForKey:key]];
        }
        pairs = [[NSMutableDictionary alloc] initWithObjects:objects forKeys:keys];
    }
    return self;
}

This is valid because I first copy over the array of keys. I then iterate through all the keys to create the array of objects. Creating the ordered pairs of keys and objects. If the code was:

- (id)initWithContentsOfDictionary:(NSDictionary *)entrys
{
    self = [super init];
    if (self != nil) {
        keys = [[NSMutableArray alloc] initWithArray:entrys.allKeys];
        objects = [[NSMutableArray alloc] initWithArray:entrys.allObjects];
    }
    return self;
}

Then there will be a problem, since the order of keys may not match the order of objects in the NSDictionary.

@zakdances
Copy link
Contributor Author

Understood.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants