2012-05-12 6 views
1

У меня есть UIButton, который вызывает метод от другого UIViewController, этот метод вызывает метод делегата, которого не происходит.Вызов метода делегата не работает

Что-то вроде:

FirstViewController 

-(void)viewWillAppear:(BOOL)animated { 
//Submit Button 
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
    [button addTarget:self 
       action:@selector(someMethod) 
    forControlEvents:UIControlEventTouchDown]; 
    [button setTitle:@"Submit" forState:UIControlStateNormal]; 
    button.frame = CGRectMake(100.0, 120.0, 80.0, 40.0); 
    [self addSubview:button]; 
} 

- (void)someMethod { 

SecondViewController *viewC = [[SecondViewController alloc] init]; 
[viewC otherMethod]; 

} 

SecondViewController 

- (void)otherMethod { 

NSLog(@"Verification....."); 
[self.delegate foo:self Bar:self.text]; //not working when called the otherMethod from FirstViewController 

} 

Я знаю, что я делаю это неправильный путь.

+0

вы можете предоставить немного больше вашего кода, чтобы мы могли видеть, что не так? – zahreelay

+1

Что вы видите, если вы измените строку ведения журнала на 'NSLog (@" Verification .....% @ ", self.delegate);'? –

+0

@PhillipMills Я вижу «Проверка ...... (null)». –

ответ

3

Очень простой пример того, как протоколы и делегаты работают в Objective-C

@class A; 
@protocol DelegateName<NSObject> 
@optional 
    - (void)doSomething:(NSString *)text; 
@end 

@interface A: NSObject { 
    NSString *bar; 
    id <DelegateName> delegate; 
} 

@property (nonatomic, retain) NSString *bar; 
@property (nonatomic, assign) id <DelegateName> delegate; 

- (void)someAction; 

@end 

Это ваш протокол декларация. Затем, когда вы вызываете метод делегата, для вызова метода делегата вам нужен объект класса. В вашем случае это vc. Вы устанавливаете делегат следующим образом:

[vc setdelegate: self]; 

Затем вы вызываете метод, как и вы.

Посмотрите, не хватает ли вы какой-либо точки из этого примера.

+0

Где задан setdelegate? Вам нужно написать этот метод? – drlobo

+0

делегат установлен как свойство, поэтому вам не нужно это делать. – zahreelay

1

Попытайтесь понять, как работают методы делегата.

@protocol CPUPerformanceDelegate <NSObject> 

-(void)getUsedCpuOperations:(float)percent; 
-(void)getKernelCpuOperations:(float)percent; 
-(void)getIdleCpuOperations:(float)percent; 
-(void)getUserCpuOperations:(float)percent; 
-(void)getNiceCpuOperations:(float)percent; 

@end 

@interface CPUPerformance : NSObject{ 

    processor_info_array_t   cpuInfo, prevCpuInfo; 
    mach_msg_type_number_t   numCpuInfo, numPrevCpuInfo; 
    unsigned      numCPUs; 

    NSLock       *CPUUsageLock; 



} 
@property(nonatomic,assign)id<CPUPerformanceDelegate>delegate; 
@property(nonatomic,retain)NSTimer       *updateTimer; 
@end 

Тогда

#import "CPUPerformance.h" 



@implementation CPUPerformance 
@synthesize delegate,updateTimer; 
- (void)updateInfo 
{ 
idlepercent = ((idle/total)*100); 
       userpercent = (user/total)*100; 
       syspercent = (sys/total)*100; 
       nicepercent = (nice/total)*100; 
       inUsepercent = (inUse/total)*100; 
[delegate getIdleCpuOperations:idlepercent]; 
      [delegate getKernelCpuOperations:syspercent]; 
      [delegate getNiceCpuOperations:nicepercent]; 
      [delegate getUsedCpuOperations:inUsepercent]; 
      [delegate getUserCpuOperations:userpercent]; 
} 

и, наконец,

#import "CPUPerformance.h" 
@interface SpecProjectFirstViewController : UIViewController<UITableViewDataSource,UITableViewDelegate,CPUPerformanceDelegate>{ 

    //Ivars 

    NSMutableArray     *processArray; 
    //User Interface Object 
    UILabel       *cpuUsage; 
    UILabel       *cpuIdle; 
    UILabel       *cpuUser; 
    UILabel       *cpuNice; 
    UILabel       *cpuKernel; 
    IBOutlet UITableView   *tableViews; 
    CPUPerformance     *cpuObject; 

} 
================= 

#import "SpecProjectFirstViewController.h" 


@implementation SpecProjectFirstViewController 

-(void)getIdleCpuOperations:(float)percent{ 

    [cpuIdle setText:nil]; 

     [cpuIdle setText:[NSString stringWithFormat:@"Idle :%.0f %%",percent]]; 
    [cpuIdle setTextAlignment:UITextAlignmentCenter]; 
} 

-(void)getKernelCpuOperations:(float)percent{ 
    [cpuKernel setText:nil]; 

    [cpuKernel setText:[NSString stringWithFormat:@"Kernel :%.0f %%",percent]]; 
    [cpuKernel setTextAlignment:UITextAlignmentCenter]; 
} 


-(void)getNiceCpuOperations:(float)percent{ 
    [cpuNice setText:nil]; 

    [cpuNice setText:[NSString stringWithFormat:@"Nice :%.0f %%",percent]]; 
    [cpuNice setTextAlignment:UITextAlignmentCenter]; 
} 

-(void)getUsedCpuOperations:(float)percent{ 

    [cpuUsage setText:nil]; 
    [cpuUsage setText:[NSString stringWithFormat:@"Used :%.0f %%",percent]]; 
    [cpuUsage setTextAlignment:UITextAlignmentCenter]; 
} 
+0

Я уже это сделал. Это не вызов, когда я вызываю otherMethod из FirstViewController. –

0

Принято утверждать, что делегат отвечает на метод, который вы хотите позвонить, так что ваш метод otherMethod должен быть реализован, как это, добавив больше протоколирование, чтобы помочь отладки:

- (void)otherMethod 
{ 
    NSLog(@"delegate = %p", self.delegate); 

    if ([self.delegate respondsToSelector:@selector(foo::)]) 
    { 
     NSLog(@"Calling delegate foo"); 
     [self.delegate foo:self Bar:self.text]; 
    } 
    else 
    { 
     NSLog(@"Delegate doesn't respond to foo"); 
    } 
} 
Смежные вопросы