2015-10-06 6 views
0

Ниже приведен мой код, нет ошибки, но селектор не отвечает.пользовательский deleget не отвечает ToSelector

Код в ExampleTableviewSubProductDetail.h

@protocol EnterAmountDelegate <NSObject> 

-(void)titlechange:(NSInteger)amount; 

@end 

@class ASIFormDataRequest; 
@interface ExampleTableviewSubProductDetail : UIViewController<UIScrollViewDelegate> 
{ 
} 
@property (nonatomic, strong) id <EnterAmountDelegate>delegate; 

Код в ExampleTableviewSubProductDetail.m

@implementation ExampleTableviewSubProductDetail 
    @synthesize delegate; 
- (void)viewWillAppear:(BOOL)animated 
{ 
[super viewWillAppear:animated]; 

if([delegate respondsToSelector:@selector(titlechange:)]) 
{ 
    //send the delegate function with the amount entered by the user 
    [delegate titlechange:20]; 
} 

код в HostProductdetailViewController.h

#import "ViewPagerController.h" 
#import "ExampleTableviewSubProductDetail.h" 

@interface HostProductdetailViewController : ViewPagerController <ViewPagerDataSource, ViewPagerDelegate, EnterAmountDelegate> 
{ 
} 

код в HostProductdetailViewController.m

- (void)viewDidLoad { 
[super viewDidLoad]; 
self.dataSource = self; 
self.delegate = self; 

} 
-(void)titlechange:(NSInteger)amount 
    { 
    NSLog(@"sdfsf"); 
    } 

В viewwillapper следующая строка всегда возвращает ложь

if([delegate respondsToSelector:@selector(titlechange:)]) 

Пожалуйста, дайте мне знать, если я что-то не хватает.

Благодаря

+0

Что такое иерархия классов 'ViewPagerController'? –

ответ

2

При нажатии из HostProductdetailViewController в ExampleTableviewSubProductDetail вам необходимо установить exampleTableviewSubProductDetail.delegate = Автономный

+0

Спасибо @krisJones Это сработало ... Было бы здорово, если бы вы могли дать некоторое объяснение .... :) – Satish

+0

Вам нужно установить exampleTableviewSubProductDetail.delegate для себя, чтобы делегат классов был установлен, иначе делегат не будет задавать. Подумайте об этом как о настройке переменной. Поскольку HostProductdetailViewController соответствует EnterAmountDelegate, мы можем установить этот контроллер как делегат exampleTableviewSubProductDetail. Надеюсь, это объяснит это. http://www.raywenderlich.com/46988/ios-design-patterns в «Как использовать шаблон делегата» дает хорошее объяснение – KrisJones

0

Скорее всего вам не хватает self:

if([self.delegate respondsToSelector:@selector(titlechange:)]) 

Вы должны следить за этим вещи. Делегат в вашем случае ближе к указателю функции, а затем к фактическому объекту. Вы также можете получить доступ к нему через _delegate.

+0

Спасибо за ответ, я тоже пробовал, но все равно не повезло .. – Satish

+0

Затем установите точку останова там и запишите, что является вашим делегатом. Записывать в консоль «po [делегировать класс]» в точке останова.Также проверьте, действительно ли делегат присутствует (но нет). –

1

Как я вижу, некоторые другие потенциально опасные вещи в вашем коде пытаются проверить этот пример. Он состоит из 2 простых классов, которые связаны через делегат. Следите за сильными ссылками на делегатов, поскольку этот ваш код приведет к циклу сохранения и вызовет утечку памяти.

Протокол:

// defining a custom protocol 
@protocol PingProtocol <NSObject> 
- (void)didPing; 
@end 

Ping класс:

// 
// This class will be able to send notifications via delegate for the protocol PingProtocol 
// Any object that implements PingProtocol will be able to assign itself to the delegate property and will be notified to all protocol methods 
// 
@interface PingClass : NSObject 

// The listener object that implements PingProtocol 
// Note this should be weak or there will a retain cycle 
@property (nonatomic, weak) id<PingProtocol> delegate; 

@end 

@implementation PingClass 

// Some event that happens will check if the delegate actually implements this method and call it. 
// The respondsToSelector is not necessary in this case since the method is not optional though. 
- (void)onEvent:(id)sender 
{ 
    if([self.delegate respondsToSelector:@selector(didPing)]) 
    { 
     [self.delegate didPing]; 
    } 
} 

// Will create a timer which will call onEvent: every second. 
// Note there should be some way to invalidate the timer as this will cause a memory leak for the PingClass 
- (void)startPing 
{ 
    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(onEvent:) userInfo:nil repeats:YES]; 
} 

@end 

СЛУШАТЕЛЬ:

// 
// This class will listen to PingProtocol methods. 
// It will need to implement all non-optional methods defined by PingProtocol 
// 
@interface ListenerClass : NSObject<PingProtocol> 

@property (nonatomic, strong) PingClass *someClass; 

@end 

@implementation ListenerClass 

// will create a PingClass object and asign itself as a delegate to start listening to delegate methods 
- (void)startListening 
{ 
    self.someClass = [[PingClass alloc] init]; 
    self.someClass.delegate = self; 
    [self.someClass startPing]; 
} 
// A protocol method 
- (void)didPing 
{ 
    NSLog(@"Ping"); 
} 

@end 
+0

Спасибо за ваше драгоценное время и силы ... Я рассмотрю эти изменения в моем коде ... :) – Satish