Domanda

I thought that the answer to this question might be very easy to find but in fact it is not. I t is basically about a best practice in MVC but I need a more specific answer to Cocoa's implementation of MVC.

Let's say you have a MainView which displays data from an mutable array via Bindings and the option to add a new Item to this array. Now, the data added to the array might be more complex and might even need validation before it can be added to the array or an object of my data class can be created. So, I have added an new MVC or to be more specific VC pair to my project which is a view where all data can be entered and a button to save it. A click action on the save button will cause the validation to start and should then, eventually, add the data to the array if the validation was successful.

I am wondering which is the best solution to access the array from the AddViewController. A shared mutable array? Setting a property in the AddViewController?

For someone who is used to MVC the answer might be quite easy. Furthermore, I am able to access the array but I really want to know which is the best way to do so.

È stato utile?

Soluzione

Delegate concept is the answer to all your problems!

Once data validation is successful pass the data to your MainView controller to be added to the array :)

Detail: Your AddViewController should have a protocol, and delegate property

@protocol AddViewControllerDelegate <NSObject>

-(void)addViewController:(AddViewController*)addViewController didCompleteWith:(id)data;

@end

@interface AddViewController : SuperClass

@property (nonatomic,weak)id<AddViewControllerDelegate>delegate;
...

@end

Your main view controller should implement this protocol, and set it self as AddViewController delegate.

Upon validating the data AddViewController should call protocol defined method on the delegate.

-(void)dataValid:(id)data {
...
[self.delegate addViewController:self didCompleteWith:data]
...
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top