views:

40

answers:

1

Hi all,

I am new to cocoa bindings so I tried to make a simple application which will simply calculate avg of employees salary and display it in a text field, using cocoa bindings. I followed these steps:

  1. Made the model class : Person with one property for now -

    @property (readwrite, assign) int salary;

  2. In the application delegate class I initialized a mutable array : personArray with certain objects like this:

    Person *person1 = [[Person alloc] init];
    person1.salary = 5000;
    
    
    Person *person2 = [[Person alloc] init];
    person2.salary = 15000;
    
    
    Person *person3 = [[Person alloc] init];
    person3.salary = 7000;
    
    
    Person *person4 = [[Person alloc] init];
    person4.salary = 9000;
    
    
    Person *person5 = [[Person alloc] init];
    person5.salary = 11000;
    
    
    personArray= [[NSMutableArray alloc] initWithObjects:person1, person2, person3, person4, person5,nil];
    
  3. In IB I dropped a NSArrayController object, set its mode as Class - Person, added key salary in attribute pane. Then in bindings pane, binded contents array to ApplicationDelegate class with model key path set to self.personArray.

  4. Dropped a NSTextField on window. Binded its value to ArrayController object. Assigned controller key as - arrangedObjects. Assigned Model key path to @avg.salary

When I executed the application I found no value being displayed in the text field.

Can anyone suggest me where I may be wrong or some other best way to accomplish it

Thanks,

Miraaj

A: 

The problem reported above is resolved now, I did following improvements to resolve it:

  1. I declared property for - personArray in ApplicationDelegate class.

  2. In place of assigning Person objects directly to personArray, I first assigned them to a temporary array and then I assigned it to personArray using: -setValue:forKey: method.

It now works as intended :)

Miraaj
If you declared a property, then you can send yourself a `setPersonArray:` message or assign to the property (same thing); you don't need to use KVC. Using KVC when you don't need to is a good way to have avoidable typos causing bugs. Also, don't forget to release the temporary array according to the memory management rules.
Peter Hosey
ok.. once again thanks :)
Miraaj