为了账号安全,请及时绑定邮箱和手机立即绑定

viewDidLoad?没有报错,但是就是传值不成功?为什么啊

viewDidLoad?没有报错,但是就是传值不成功?为什么啊

C
浮云间 2023-04-13 15:15:39
比如A,B两个view,值从A传到B。在B里面写A *av = [[A alloc]init];[av setDelegate:self]和在A里面写B *bv = [[B alloc]init];[self setDelegate:bv];这句setDelegate要放哪里呢?viewDidLoad?没有报错,但是就是传值不成功。能给我一点提示吗?代码#import <Foundation/Foundation.h>@protocol delegate <NSObject>-(void)passString:(NSString *)string;@end#import <UIKit/UIKit.h>#import "labelViewController.h"#import "delegate.h"@interface buttonViewController : UIViewController @property (weak, nonatomic) IBOutlet UIButton *button;@property (weak,nonatomic) id <delegate> delegate; - (IBAction)buttonPress:(UIButton *)sender;@end#import "buttonViewController.h"@interface buttonViewController ()@end@implementation buttonViewController- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];    if (self) {        // Custom initialization     }    return self; } - (void)viewDidLoad { labelViewController *lv = [[labelViewController alloc]init]; [self setDelegate:lv];         [super viewDidLoad]; // Do any additional setup after loading the view.} - (IBAction)buttonPress:(UIButton *)sender { [self.delegate passString:sender.currentTitle]; [self performSegueWithIdentifier:@"push" sender:self]; }@end#import <UIKit/UIKit.h>#import "delegate.h"@interface labelViewController : UIViewController <delegate>@property (weak, nonatomic) IBOutlet UILabel *label;@end#import "labelViewController.h"@interface labelViewController ()@end@implementation labelViewController- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];    if (self) {        // Custom initialization     }    return self; } - (void)viewDidLoad {     [super viewDidLoad];    // Do any additional setup after loading the view.} - (void)passString:(NSString *)string{ self.label.text = string; NSLog(@"%@",self.label.text); }@end
查看完整描述

2 回答

?
肥皂起泡泡

TA贡献1829条经验 获得超6个赞

应该是

A *av = [A alloc]init];
[av setDelegate:self]

吧,问题里A是个类名,怎么能setDelegate呢


查看完整回答
反对 回复 2023-04-17
?
芜湖不芜

TA贡献1796条经验 获得超7个赞

如果理解了delegate的意思,就知道如何使用delegate了。

简单来说,就是某件事情发生了,我处理不了,需要借助外部力量才行。好比我要出远门,走肯定不现实,这时就要借助交通工具,如:汽车、火车、飞机。只要这些交通工具都实现了某个协议,确保调用该交通工具的某个方法时不会出错。

如果我主动去设置delegate,如:我.delegate = 火车。没有错,但没什么意义,delegate的灵活性就不存在了,我被某个交通工具绑死了。所以 我.delegate 需要在外部设置。对我来说,只要在适当的时候执行 我.delegate.go 就行了。要是delegate是飞机就爽了,是一辆临客就认了吧。


查看完整回答
反对 回复 2023-04-17
  • 2 回答
  • 0 关注
  • 93 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信