Assigning a variable from another class

74 Views Asked by At

I have a UIView with a UIButton created in 1 class: "viewClass". In my mainVC class, I called viewClas and I needed to call a method in mainVc when the button is selected, so I created a protocol. (I hope that was clear.)

Here's how I set up the protocol and delegate:

viewClass.h

@protocol ViewClassDelegate

-(void)buttonWasClicked;

@end

...
@property (nonatomic, strong) id<ViewClassDelegate> delegate;

viewClass.m

[submitButton addTarget:self action:@selector(submitButtonTapped) forControlEvents: UIControlEventTouchUpInside];

- (void)submitButtonTapped {
    [self.delegate buttonWasClicked];
}

mainVC.m

// Imported and called the delegate in mainVC.h. Then in .m I set the delegate

-(void)buttonWasClicked {
    // Perform some action
}

Is there a way to pass an NSString to buttonWasClicked? I don't mean like this:

- (void)buttonWasClicked:(NSString *)myString

because myString has no value unless I assign it in mainVC method. I want to assign it in submitButtonTapped (which is in myView.m).

Basically, I want something like this:

- (void)textFieldDidBeginEditing:(UITextField *)textField

In that method, it knows what textField is without me defining it when I use that method.

Hope this is clear. If someone can explain it better, feel free to edit it. If you need more clarification, please ask in the comments.

2

There are 2 best solutions below

2
On BEST ANSWER

viewClass.h

@protocol ViewClassDelegate

-(void)buttonWasClicked:(NSString *)aString;

@end

viewClass.m

[submitButton addTarget:self action:@selector(submitButtonTapped) forControlEvents: UIControlEventTouchUpInside];

- (void)submitButtonTapped {
    [self.delegate buttonWasClicked:@"this is a string"];
}

mainVC.m

// Imported and called the delegate in mainVC.h. Then in .m I set the delegate

-(void)buttonWasClicked:(NSString *)aString {
    // aString = this is a string 
}
2
On

I'm not sure if this is what you want:

@protocol ViewClassDelegate

-(void)buttonWasClicked:(NSString*)value;

@end

...
@property (nonatomic, weak) id<ViewClassDelegate> delegate;

[submitButton addTarget:self action:@selector(submitButtonTapped:) forControlEvents: UIControlEventTouchUpInside];

- (void)submitButtonTapped:(UIButton*)sender {
    [self.delegate buttonWasClicked:stringToSendWhereverHasBeenDefined];
}

...

-(void)buttonWasClicked:(NSString*)value {
    // Perform some action
}