cocoadatasourcenscombobox

Custom datasource with a NSComboBox not displaying anything


Greetings I have the following problem trying to set a datasource in an NSComboBox.

This is my custom datasource class:

@interface CComboDatasource : NSObject <NSComboBoxDataSource> {
@private
    NSMutableArray* values;
}
@property (nonatomic,retain) NSMutableArray* values;
-(int)itemCount;

@end


@implementation CComboDatasource
@synthesize values;

- (id)init
{
    self = [super init];
    if (self) {
        // Initialization code here.
        values=[[NSMutableArray alloc] init];

        [values addObject:@"A"];
        [values addObject:@"B"];
        [values addObject:@"C"];
    }

    return self;
}


- (NSInteger)numberOfItemsInComboBox:(NSComboBox *)aComboBox
{
    return [values count];
}

- (id)comboBox:(NSComboBox *)aComboBox objectValueForItemAtIndex:(NSInteger)index
{
    return [values objectAtIndex:index];
}

- (void)dealloc
{
    [values release];
    [super dealloc];
}

@end

Later in another file I connect my IBOutlet with my NSComboBox object (c_box) and I set the datasource (CComboDatasource* data_source).

 [c_box setUsesDataSource:TRUE];
 [c_box setDataSource:data_source];
 [c_box setEditable:NO];

After the previous actions nothing is displayed in the combo box, what am I doing wrong?


Solution

  • What you have looks basically right to me. I can think of a few things you could try:

    1) Try temporarily replacing "return [values count]" with "return 5" and replacing "return [values objectAtIndex:index]" with "return @"arbitraryString"". If "arbitraryString" then shows up in the combobox, you'll know the problem is with the "values" array.

    2) Try initializing the "values" array like this:

    values = [NSMutableArray array];
    

    (It's a convenience method offered in NSArray.)

    If you stick with an alloc-init method, you should make a separate temporary array that way, assign it to "values," then release it. Otherwise, since you've propertized "values" with "retain," you're retaining it twice.

    3) Try adding this line at the end of your c_box calls:

    [c_box reloadData];
    

    And any time you change the data source array, call this again.

    4) I don't see why separating the data source class from the class controlling the combobox should be a problem, but if it's still not working, try making the window/view controller that owns the combobox outlet the class that implements the NSComboBoxDataSource protocol (the numberOfItemsIn and objectValueFor methods), and either put "values" in this controller class or give this class access to "values."

    Hope that helps.