Search code examples
cocoacore-datakey-value-observingnsarraycontroller

How to get some values from CoreData-Entities to code


I've created in my CoreData app an entity with some attributes. Imagine a tableview and a bound NSArrayController. With both I create (and edit) my entity "instances". My question is how I can get the values of these attributes to my code. If there are more questions: http://twitter.com/xP_ablo


Solution

  • You need to somehow get a reference to the NSArrayController. If you are loading the NIB yourself, you can add an IBOutlet instance to the class that is set as the NIBs "File Owner". When you load a nib, you supply the instance of the NIB's "File Owner" class as the owner. If you are not loading the NIB yourself (i.e. it's loaded automatically by Cocoa as the MaineMenu nib/xib of your app), then create an instance of your own class in the nib and add an IBOutlet to that instance. You create an IBOutlet in your class like this:

    @interface MyClass : NSObject { //of course your class doesn't have to be a direct descendent of NSObject
        IBOutlet NSArrayController *arrayController;
    }
    
    @property (retain,nonatomic,readwrite) IBOutlet NSArrayController *arrayController;
    
    ...
    
    @end
    
    @implementation
    @synthesize arrayController;
    
    - (void)dealloc {
        [arrayController release];
        [super dealloc];
    }
    @end
    

    Connect the IBOutlet in your class to the NSArrayController (controll-click on the File Owner in the first case or the instance of your class in the second case above) and drag to the NSArrayController. When you release the mouse, you'll get a pop-up of the IBOutlets in the drag source. Select the IBOutlet you created (e.g. "arrayController" in the example above).

    One the nib is loaded (i.e. after awakeFromNib is called in your class), you can access the arrayController via the outlet:

    NSArray *content = [[self arrayController] arrangedObjects];
    

    and you can now do what you please with the values in the array.