DISABLE ADBLOCK

ADBlock is blocking some content on the site

ADBlock errore

Fastest way to load an NSComboBox from an 8000 item plist

StackOverflow https://stackoverflow.com/questions/18180514
 Checked

Question

I have a plist that is basically a list of 8000 usernames. I load this into an NSDictionary, then an array of sorted keys (because the list isn't sorted when I get it) then loop through loading into an NSComboBox.

This works, but can take a few seconds to populate the combo box.

Here's my code:

// in my .h
IBOutlet NSComboBox *comboUserList; // which is connected to a combo box in my .xib

// in my .m

// userInfoPlist is an NSString path to the file
NSDictionary *userList = [NSDictionary dictionaryWithContentsOfFile:userInfoPlist];

// sort user info into an array

NSArray* sortedKeys = [userList keysSortedByValueUsingSelector:@selector(caseInsensitiveCompare:)];

// then populate the combo box from userList in the order specified by sortedKeys

for ( NSString *usersKey in sortedKeys) {
    [comboUserList addItemWithObjectValue:[userList objectForKey:usersKey]];
}

So this works, but for 8000 odd entries it takes some noticeable time to populate the combo box (only a second or two on a 2011 MAcBook Air, but still noticeable). Is there a faster way to use either the NSDictionary or NSArray as a data source rather than do it in a for loop?

Solution

User External Data Source.

[mEmailListBox setUsesDataSource:YES];
[mEmailListBox setDataSource:self];  
/*
If you use setDataSource: before setUsesDataSource:, setDataSource: throws an exception.
*/
- (NSInteger)numberOfItemsInComboBox:(NSComboBox *)aComboBox;
{
    return [DatSource count];//DatSource NSArray
}
- (id)comboBox:(NSComboBox *)aComboBox objectValueForItemAtIndex:(NSInteger)index;
{
    return DatSource[index];
}  

Take a look at Combo Box Programming Topics

You can also load data in background with the help of noteNumberOfItemsChanged and reloadData methods

OTHER TIPS

You should use a data source instead of providing the values directly. Use -[NSComboBox setUsesDataSource:] and -[NSComboBox setDataSource:] to set your datasource then implement NSComboBoxDataSource protocol on your controller.

See: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Protocols/NSComboBoxDataSource_Protocol/Reference/Reference.html#//apple_ref/occ/intf/NSComboBoxDataSource

If you do not need eact behavior like this code when you sort keys and put values into NSComboBox you can do it different.

If it is OK to put sorted keys or values you can use one call instead of looping:

[comboUserList addItemsWithObjectValues:sortedKeys];

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow