ios - 从自定义委托(delegate)方法检索数据

标签 ios objective-c cocoa-touch

这是我第一次尝试创建自定义委托(delegate)。我创建了一个小测试来检查基本功能。

基本上是shareRoutine我的委托(delegate)中的方法被调用,但返回值在NSLog上有效的是 NULL这意味着我的- (NSString*) shareRoutineDel未正确调用或检索。

有人能指出为什么这不起作用吗?

我已经包含了<shareDelegate>在这个UIViewController的.h文件中,但还没有做更多的事情,我的委托(delegate)方法是在另一个类中通过调用的。

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

我的委托(delegate)类

.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

最佳答案

如果你没有委托(delegate),你就不能向它请求任何东西,所以你将永远拥有 null。

尝试在创建测试实例后立即设置委托(delegate):

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

在你的问题中,你说“我的委托(delegate)方法是通过...在另一个类中调用的”,这可能意味着上面的内容不正确,但很难说。只需让它与 2 个类一起工作,直到您了解它是如何工作的。

关于ios - 从自定义委托(delegate)方法检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17611303/

相关文章:

iphone - 添加 Core Data 对象后 tableView 未更新

ios - 安装 Xcode 9.0 Beta 后 Xcode 8.3.2 中缺少模拟器

ios - viewControllerAfterViewController : does not get called with UIPageViewController

ios - 检测用户点击通知

cocoa-touch - 设置属性后 NSTextAttachment 图片消失

ios - '-[__NSCFNumber 行] : unrecognized selector sent to instance 0xb416910'

ios - 在 ios 上使用带有 swift4.2 的 opencv 函数

android - Nativescript 应用程序可以解压缩 zip 文件吗?

ios - 可以在 Swift 应用程序和后端之间交换对象吗?

iphone - 无法编辑 UITableView 框架.y