Search code examples
objective-cxcodemacoscocoansarraycontroller

How do I configure an NSArrayController to work with my NSMutableArray (so I can filter a table with NSSearchField)?


I've been having a bit of trouble understanding how NSArrayController works. I have managed to get my NSTableView to populate with a NSMutableArray, but I'm lost when I try to get objects into an NSArrayController.

I need to get my data into an NSArrayController so I can later filter the table with an NSSearchField. This is my current 'add' function in my TableController class. Is there any way I can bind an Array Controller to TableController and just add data from this method?

In the code, MyMain is an NSMutableArray. I originally used the class storedFile to organize my data, but when I had to conform to property-list syntax I found it easier to use an NSDictionary. If I have to use storedFile for my Array Controller implementation I can do that with the legacy code.

-(IBAction)add:(id)sender{


    storedFile *store = [[storedFile alloc]init];

    NSDictionary *newDict = [[NSMutableDictionary alloc]init];


    //legacy code, changed to comply plist properties
    store.name = enter_name.stringValue;
    store.pdf = pdfLocation;
    store.site = website.stringValue;
    //End of legacy code. I may have to use this for an Array Controller?


    [newDict setValue:enter_name.stringValue forKey:@"name"];
    [newDict setValue:pdfLocation forKey:@"pdf"];
    [newDict setValue:website.stringValue forKey:@"site"];

    [myMain addObject:newDict];


    [tableView reloadData];
    [enter_name setStringValue:@""];
    [website setStringValue:@"http://"];
    [pdf_selected setStringValue:@"NO PDF SELECTED"];
    pdfLocation = @"NO PDF SELECTED!";


    [addWindow close];
    newDict = [[NSMutableDictionary alloc]init];
    [mainWindow orderFront:self];




}

Solution

  • You can take one more array inside that you can just assign your main array. And then use NSPredicate for filtering the data in your search field like that below:-

    Also implement the below in controlTextDiChange delegate method.

    NSArray *secondaryArr=[myMain copy];
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF CONTAINS[CD] %@", @"yourTxt"];
    NSArray *filteredArray = [secondaryArr filteredArrayUsingPredicate:pred];