ios - Objective-C 协议(protocol)委托(delegate)

标签 ios delegates protocols

我了解委托(delegate)的工作原理,已经了解了一些示例,但现在有了用于测试的基本应用程序,我似乎还没有掌握它,

这里是我的代码:

类定义协议(protocol)> *.h

#import <Foundation/Foundation.h>
@protocol protoPerra <NSObject>

-(void) dimeTuNombre:(NSString *) s;
@end

@interface MyClassic : NSObject {
id<protoPerra> _delegate;  
}
@property (assign) id<protoPerra> delegate;
@end

类实现协议(protocol)> *.m

#import "MyClassic.h"

@implementation MyClassic
@synthesize delegate = _delegate;
- (id)init
{
self = [super init];
if (self) {
    // Initialization code here.
    [[self delegate] dimeTuNombre:@"pinguete"];
 }

return self;
}
-(void) dealloc {
[_delegate release];
_delegate = nil;
[super dealloc];
}
@end

类采用协议(protocol):

#import "MyClassic.h" @interface MainViewController : UIViewController (protoPerra)

.m

#import "MainViewController.h"
  @implementation MainViewController
  -(void) dimeTuNombre {
   NSLog(@"ss9!! tkt");
   }
   - (void)viewDidLoad {
[super viewDidLoad];

UILabel *lava = [[[UILabel alloc] initWithFrame:CGRectMake(30, 100, 100, 20)] autorelease];
lava.text = @"lava ss9";
[self.view addSubview:lava];

MyClassic *pirr = [[[MyClassic alloc] init ] autorelease];
[pirr setDelegate:self];
 }
 -(void) dimeTuNombre:(NSString *)s {
   NSLog(@"%@",s);
  }
  @end

那么这个简单的示例中缺少什么才能使其与我的委托(delegate)一起工作?

非常感谢!

请注意,我使用了 <> 的 () insted [在采用类的 .h 中],就像我使用 Chevrons 一样,代码消失了

最佳答案

您在 MyClassic init 中调用了委托(delegate)方法 (dimeTuNombre:),但委托(delegate)尚未设置,因此您要么需要重新考虑何时调用 dimeTuNombre:,要么重构 MyClassic 类以具有类似的构造函数

-(id)initWithDelegate:(id<protoPerra>)delegate

而不仅仅是简单的初始化。

澄清一下,在您当前的代码中,当您执行 [pirr setDelegate:self] 时,您在 MainViewController.h 中设置了委托(delegate); - 将 MyClassic 属性的值“委托(delegate)”设置为 MainViewController 的当前实例。请注意,当您调用 MyClassic 的 init 时,委托(delegate)尚未设置,因此 [[self delegate] dimeTuNombre:@"pinguete"];调用什么都不做(此时委托(delegate)为 nil)。

您可以按如下方式更改 MyClassic 构造函数:

-(id)initWithDelegate:(id<protoPerra>)aDelegate
{
self = [super init];
if (self) {
    _delegate = aDelegate;
    // Initialization code here.
    [[self delegate] dimeTuNombre:@"pinguete"];
 }

return self;

}

然后代替这个:

MyClassic *pirr = [[[MyClassic alloc] init ] autorelease];
[pirr setDelegate:self];

你会这样做:

MyClassic *pirr = [[[MyClassic alloc] initWithDelegate:self ] autorelease];

这会起作用,但请注意,委托(delegate)通常用于各种通知 - 例如按钮报告它已被单击或套接字表示它已收到一些数据。

关于ios - Objective-C 协议(protocol)委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7314099/

相关文章:

ios - 一个delegate可以申请两个VC吗

android - 与 MIFARE Plus SL3 通信(命令)

ios - 在 UITableView 中带导航的 UITableView

delegates - 使用 Windsor 容器注入(inject) Func<T>

iphone - 相机胶卷和照片库有什么区别?

c# - 在不使用iF字的情况下,根据 bool 结果触发函数

protocols - FIX : Client asked for GapFill but I want to send a SequenceReset instead. 它应该有什么顺序?

xcode - swift 2.0 测试版 : are protocols kinda broken in Xcode beta 5?

ios - 如何以编程方式向 UIBarButtonItem 添加填充

ios - 如何在iOS主屏幕上将“应用程序名称”设置为2行(或更多行)?