简体   繁体   中英

class instance method in delegate method is not called

There are 3 classes Red, Blue and Yellow. Whenever a button is pressed yellow class informs the blue class and passes back a string through delegate. This bit works fine. Well now the blue class is trying to call the red class instance method displayString inside the delegate implementation method. But this instance method is never called for some reason. Upon debugging i found that self.red is null in [self.red displayString:col]; . But i use self.red in another class instance method of Blue class and self.red is NOT NULL then. Is something missing here

@interface RedClass : NSObject 
     -(void)displayString:(NSString*)str;
@end

@implementation RedClass
     -(void)displayString:(NSString*)str
     {
         NSLog(@"The string:%@",str);
     }
@end

// BlueClass.h

    @interface BlueClass:UIViewController<YellowDelegate>
         @property (nonatomic, strong) RedClass *red;
    @end

//the class that is implementing the delegateExample and calling the class instance method of example class

// BlueClass.m

   @implementation BlueClass

   - (void)colorChanged:(NSString*)col
   {
      [self.red displayString:col];
   }
   @end

//the YellowClass

  @protocol YellowDelegate<NSObject> 
     -(void)colorChanged:(NSString *)col;
  @end
  @interface YellowClass:UIView
      @property (nonatomic, weak) id <YellowDelegate> delegate;
  @end

//YellowClass.m @implementation YellowClass

  (IBAction)btnPressed:(id)btn
   {
        [self.delegate colorChanged:@"yellow"];
   }
  @end

Show how you create and connect all the objects. Where do you allocate an instance of RedClass and assign it to the red @property ? Where do you set the delegate?

If the answer is that you don't, then your code does nothing because, in Objective-C, nil eats messages .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM