Shadrax
Shadrax

Reputation: 57

How do I pass a value to a method in Objective C

I'm new to Obj-C and I have run in to a very, very basic mental block that's making me feel a little stupid. I want to pass a variable from one method to another in an purely objective-C way. So far I'm stuck and have resorted to writing it in C. In C it goes as follows;

//detect the change in the segmented switch so we can; change text
- (IBAction)switchChanged:(id)sender
{
    NSLog(@"Switch change detected");
    //grab the info from the sender
    UISegmentedControl *selector = sender;
    //grab the selected segment info from selector. This returns a 0 or a 1.
    int selectorIndex = [selector selectedSegmentIndex];
    changeText (selectorIndex);
}

int changeText (int selectorPosition)
{
    NSLog(@"changeText received a value. Selector position is %d", selectorPosition);
    //Idea is to receive a value from the segmented controler and change the screen text accordingly

    return 0;
}

This works perfectly well, but I want to learn how to do this with objects and messages. How would I rewrite these two methods to do this?

Cheers

Rich

Upvotes: 0

Views: 3021

Answers (1)

Michael Chinen
Michael Chinen

Reputation: 18697

Actually, you will only need to rewrite one of them since - (IBAction)switchChanged:(id)sender is an objective c method.

once you have your class definition, you can rewrite the changeTextFunction as:

//detect the change in the segmented switch so we can; change text
- (IBAction)switchChanged:(id)sender
{
    NSLog(@"Switch change detected");
    //grab the info from the sender
    UISegmentedControl *selector = sender;
    //grab the selected segment info from selector. This returns a 0 or a 1.
    int selectorIndex = [selector selectedSegmentIndex];
    [self changeText:selectorIndex];
}

-(int) changeText:(int) selectorPosition
{
    NSLog(@"changeText received a value. Selector position is %d", selectorPosition);
    //Idea is to receive a value from the segmented controler and change the screen text    

    return 0;
}

Also note that you will should add to your header file:

-(int) changeText:(int) selectorPosition;

Also note that this is for adding the changeText method to the class that has the switchChanged method. Tip: use command+option+up to jump to the header file directly.

Upvotes: 1

Related Questions