MichelleJS
MichelleJS

Reputation: 759

Objective-C Model-View communication

I have a class of which an instance is created when a UIViewController is loaded. I need the instance of this class to be able to update the ViewController when certain events happen. This is how I have accomplished this:

AViewController.h

@property (weak, nonatomic) IBOutlet UIProgressView *progress;
@Property (strong, nonatomic) ClassB *classB
-(void)incrementProgressBar: (NSNumber *)currentProgress;

AViewController.m

-(void)viewDidLoad
{
    _classB = [ClassB alloc]initWithNonReleventVariable:variable];
    [_classB setInstanceViewController:self]
}
-(void)incrementProgressBaar: (NSNumber *)currentProgress;
{
    [_progressBar setProgress:[currentProgrsss floatValue] animated:YES];
}

ClassB.h

@property (strong, nonatomic)AViewController *avc;
@property (nonatomic) double progress;

ClassB.m

-(void)incrementExerciseProgress
{
    //do some calculations here
    [self.avc incremtProgressBar:[NSNumber numberWithDouble:_progress]];
}

I inherited this code from someone else and it works properly. So my question is this: Is this a "correct" way to accomplish this? I want to know if this is best practice? or if not what I could do to fix it so it was. I have some time on this project so I want to make sure I do it correctly if possible. Thanks.

Upvotes: 2

Views: 130

Answers (2)

xlarsx
xlarsx

Reputation: 991

They can share a mutable data structure (for example a NSMutableDictionary) that is affected by the events of the View, and let the other class be notified by KVO of this change, so they're totally decoupled by datastructures.

The KVO part could be improved by the MAKVONotificationCenter library :)

If you requiere an example let me know

Greetings

Luis Alejandro

Ref:

Upvotes: 2

Mohannad A. Hassan
Mohannad A. Hassan

Reputation: 1648

This way, introduced high coupling between two classes from two different layers. You can instead create a ClassBDelegate protocol.

@protocol ClassBDelegate <NSObject>
- (void) classB: (ClassB *)class hasIncrementedProgressTo:(NSNumnber *)prgoress;
@end

Make AViewController conform to it. This way, ClassB can neglect any changes in the controller layer. An instance of ClassB only needs to inform its delegate of the changes in raw data and the it's the delegate's job, i.e the view controller, to show that change using views.

Upvotes: 3

Related Questions