Search code examples
objective-ccocoansarraycontroller

How can I get number of returned results from NSArray Controller in cocoa app?


I have an NSArrayController named productsArrayController which is binded with an NSTableViev and returns records from core data. I want now programmatically to get the number of the records that are displayed in the NSTableView.

I know that I should do that from the data source (productsArrayController in my case) not from the NSTableView, so I make an outlet from my NSArrayController. Here is what I am trying to do:

- (void)viewDidLoad {
    NSArray *myArr = [_productsArrayController selectedObjects];
    NSUInteger total = [myArr count];
    NSLog(@"Total is: %ld",total);
}

Sure enough since I have no selected objects at this time, the above code returns 0, even that I have 9 records displayed in my NSTableView. Question is what should I use instead of selectedObjects to get the number of the records (9 in my case) here?


Solution

  • You can do one thing in applicationDidFinishLaunching: add

    NSError *error; 
    BOOL ok = [productsArrayController fetchWithRequest:nil merge:NO error:&error]; 
    int count = [[productsArrayController arrangedObjects] count];
    

    Answer taken from the following thread URL