2013-07-12 87 views
0

它是我第一次嘗試創建自定義代理。我創建了一個小測試來檢查基本的功能。從自定義代理方法中檢索數據

基本上在我的委託shareRoutine方法被調用,但是,NSLog valiable返回值是NULL因此暗示我- (NSString*) shareRoutineDel不會被調用或正確檢索。

任何人都可以指出爲什麼這不起作用?

我在這個UIViewController的.h文件中包含<shareDelegate>,但沒有做更多的事情,我的委託方法在另一個類中被調用。

- (IBAction)share:(UIButton *)sender { 
    _share = [[share alloc]init]; 
    [_share shareRoutine]; 
} 
- (NSString*) shareRoutineDel { 
    NSString* a= @"test"; 
    return a; 
} 

我委託類

.h 
@class share; 
    @protocol shareDelegate 

    @optional 
    -(NSString*) shareRoutineDel; 
    @end 

    @interface share : NSObject 
    @property (nonatomic, weak) id<shareDelegate> delegate; 
    - (void) shareRoutine; 
    @end 

.M

#import "share.h" 

@implementation share 
@synthesize delegate; 

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

-(void) shareRoutine { 
    NSString * response = [[self delegate] shareRoutineDel]; 
    NSLog(@"check: %@",response); 
} 
@end 
+0

你在哪裏設置任何代表? – Wain

+0

我沒有在任何地方設置任何代表。我試過在''''''''''''''''中做這件事,但我這樣做的方式是錯誤的,並沒有編譯。 –

回答

1

如果沒有委託你不能要求它什麼,所以你總是有空。

嘗試設置您所創建的測試實例剛過委託:

_share = [[share alloc]init]; 
_share.delegate = self; 
[_share shareRoutine]; 

在你的問題,你說「我的委託方法是通過...稱爲另一個類」這可能意味着上述ISN」 t正確,但很難說。直到你明白它是如何工作的。

相關問題