0

Starting point
I have a class, say A, used by an UI view.
A has a delegate that should notify UI view and this one should be write something on screen.

Question
What is the best approach to achieve this feature?
Seems something like observer-observable pattern

Code

---A.h

@interface A : NSObject

@end

---A.m

@implementation A 

-(void)fooDelegate:(FooType *)sender {
      /* Here I need to notify UI (that change notificationArea.text) */
}

---UIView.h

@interface UIView : UIViewController

@property(strong, nonatomic, retain) A* a;
@property(strong, nonatomic) IBOutlet UITextField *notificationArea;

@end
Luca Davanzo
  • 21,000
  • 15
  • 120
  • 146
  • Since A has a `delegate`, wouldn't you just use the `delegate` pattern? Does A have properties that you wish to observe instead? – Aaron Wojnowski Oct 14 '14 at 15:07
  • no, when happens something in A, I had to fill a UITextField in UI View.. – Luca Davanzo Oct 14 '14 at 15:12
  • If A is only going to have one class interacting with it, use the delegate pattern and just have a delegate callback when something changes. Otherwise, if there are multiple possible observers or it isn't appropriate to have a single delegate (since other classes might want to eventually be the delegate, etc) use KVO. – Aaron Wojnowski Oct 14 '14 at 15:15
  • Just add another `delegate` on `A` to notify your `UIView` when `viewDelegate:` fires. – Aaron Wojnowski Oct 14 '14 at 15:24
  • some code could help me! – Luca Davanzo Oct 14 '14 at 15:26

1 Answers1

1

Based on the comments, I guess just code is what you're looking for...

Create your delegate protocol:

@protocol ADelegate;

@interface A : NSObject

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

@end

@protocol ADelegate <NSObject>

@optional
-(void)fooDelegate:(A *)a;

@end

Notify your delegate:

@implementation A

-(void)fooDelegate:(FooType *)sender {

    if ([[self delegate] respondsToSelector:@selector(fooDelegate:)]) {

        [[self delegate] fooDelegate:self];

    }

}

@end

Conform to the delegate protocol:

#import "A.h"
#import "MyView.h"

@interface MyView <ADelegate>

@end

@implementation MyView

-(void)fooDelegate:(A *)a {

    // update text field here

}

@end

Finally, whenever you create an instance of A, set the delegate (where self in this example is an instance of MyView:

A *a = [[A alloc] init];
[a setDelegate:self];
Aaron Wojnowski
  • 6,352
  • 5
  • 29
  • 46
  • great.. meanwhile I was reading this answer that is basically what I need http://stackoverflow.com/questions/6168919/how-do-i-set-up-a-simple-delegate-to-communicate-between-two-view-controllers ... so I'm sorry I wasted your time.. – Luca Davanzo Oct 14 '14 at 15:52