0

I've created a simple example of delegate used. The problem is when i start the application the MyClass class is called and the delegate is sent. But am not able to receive it in ViewController. Below is my code I'd like to know what i did wrong and if am understanding the delegates wrongly.

Apologies for my grammatical mistake. Thank you for helping in advance

MyClass.h

@protocol MyClassDelegate <NSObject>
@required
- (void) myClassDelegateMethod;
@end

@interface MyClass : NSObject
{
    id<MyClassDelegate> delegate_;
}
@property( nonatomic, strong ) id<MyClassDelegate> delegate_;

MyClass.m

@synthesize delegate_;

- (id)init
{
    if (self = [ super init ] )
    {
        [ self myMethodDoStuff ];
    }
    return self;
}

- (void) myMethodDoStuff
{
    [ self.delegate_ myClassDelegateMethod ];
}

ViewController.h

#import "MyClass.h"
@interface ViewController : UIViewController< MyClassDelegate >

ViewController.m

-( void ) viewDidLoad
{
    [ super viewDidLoad ];
    MyClass* class = [ MyClass new ];
    [ class setDelegate_:self ];
    [ self.view addSubView:class ];
}

The myClassDelegateMethod method in viewController.m is not being called.

-(void)myClassDelegateMethod
{
    NSLog( @"Delegates" );
}
Jaff
  • 105
  • 1
  • 17

1 Answers1

1

The problem is MyClass* class = [ MyClass new ]; call - (id)init and then call [ self myMethodDoStuff ]; .

But at this time [ class setDelegate_:self ]; wasn't called yet. It means self.delegate_ didn't point to anything(ViewController). So -(void)myClassDelegateMethod wasn't called

You should setDelegate first, somethings like:

[ class setDelegate_:self ];
[ class myMethodDoStuff ];

One more:

@property( nonatomic, strong ) id<MyClassDelegate> delegate_; 

It should be 'weak' (not strong). And you have to check valid delegate before do anything.

REF: Differences between strong and weak in Objective-C

Community
  • 1
  • 1
tuledev
  • 10,177
  • 4
  • 29
  • 49
  • Also is it possible if i make MyClass to a singleton class? Will the delegates work and is it proper to use like that in some case? – Jaff Aug 19 '15 at 03:26
  • Yes, singleton class is almost same with normal class. – tuledev Aug 19 '15 at 03:31
  • Thank you once again. Can you please explain (if possible) about giving weak in property, because i use nonatomic strong for all property i use. Almost everything i never used any other in it. – Jaff Aug 19 '15 at 03:49
  • I afraid I don't explain good. So refer the link. The key is: if strong, the object is pointed (ViewController) won't be released with ARC, you have to set delegate_ = nil to release (ViewController). But if weak, (ViewController) will be released when it's possible by ARC. e.g. in case : dismiss (ViewController), ... – tuledev Aug 19 '15 at 03:54