Search code examples
nstableviewnsmanagedobjectnsmanagedobjectcontextnsarraycontroller

How to pre-fill a NSTableView bound to an ArrayController in a Core Data ( Document based)


Here is my problem: I have a Core Data- Document based program with ARC ( Automatic Reference Counting); I want the tableView shows some data at the beginning. but I receive nothing. Here is what I have done:

1- I made a core data with Entity: MyData

enter image description here

2- then I added a NSArrayController and bound it to managedObjectContext and MyData

enter image description here

enter image description here

3- I bonded the arrayController to col0:

enter image description here

4- then made and outlet and added @synthesize for the arrayController :

enter image description here

5- Finally added this code:

  • (void)windowControllerDidLoadNib:(NSWindowController *)aController {

    [super windowControllerDidLoadNib:aController];

    for (NSUInteger i=0; i<5; i++) {

    [myArrayController add:self];
    
    [myArrayController setSelectionIndex: i];
    
    [myArrayController setValue:@"test" forKeyPath:@"selection.col0"];
    
    NSLog(@"%lu",[myArrayController selectionIndex]);
    

    } }

But this is the problem: nothing happens and the SelectionIndex shows strange numbers!!

enter image description here

Any help appreciated


Solution

  • After one month nobody answered me ! finally I could handle it:

    NSError* error;

    NSInteger count=0;
    
    NSNumber* N=[[NSNumber alloc]initWithInt:0];
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    
    NSEntityDescription * entityMyData  = [NSEntityDescription entityForName:@"MyData"
                                                      inManagedObjectContext:[self managedObjectContext]];
    
    [fetchRequest setEntity:entityMyData];
    
    
    count=[self.managedObjectContext countForFetchRequest:fetchRequest error:&error];
    
    
    
        if (count==0 ) {
            
    
            for (NSInteger i=count+1; i<RowsToAdd+count+1; i++) {
    
                N=@(i);
    
                managedObject = [NSEntityDescription insertNewObjectForEntityForName:@"MyData"
                                                              inManagedObjectContext:[self managedObjectContext]];
    
                [managedObject setValue:N forKey:@"col0"];
    
                [managedObject setValue:N forKey:@"col1"];
    
                
            }
    
           
          
        }