views:

1288

answers:

2
-(void)myButtonclick {
    NSString *data=[[NSString alloc]initWithString:@"YES U PRESSED BUTTON"];
    UIButton *refreshbutton=[UIButton buttonWithType:UIButtonTypeCustom];

    [refreshbutton setFrame:CGRectMake(15.0f, 330.0f, 150.0f, 32.0f)];
    [refreshbutton setCenter:CGPointMake(80.0f,340)];   
    [refreshbutton setBackgroundImage: normalImage forState: UIControlStateNormal];
    [refreshbutton setBackgroundImage: downImage forState: UIControlStateHighlighted];
    [refreshbutton setBackgroundImage: selectedImage forState: UIControlStateSelected];
    [refreshbutton setTitle:@"Refresh"  forState:UIControlStateNormal];
    [refreshbutton addTarget:self action:@selector(showMessage:) forControlEvents:UIControlEventTouchUpInside];
}

-(id)showMessage:(id)sender{
    // Here I want to get the value of "data" which is defined the method 
    // "myButtonclick" in the first line. how it is possible..?
}

In the above code in the method "myButtonclick" I set one NSString variable name is "data" I want to get (print there) its value (YES U PRESSED BUTTON) in the method "showMessage" when I press that button.

I know this is done using @selector variable.. but I don't know how it is done

A: 

Try looking here.

Epsilon Prime
+2  A: 
  1. String objects and data objects are two different things. Don't name a string variable “data”—you're setting yourself and anyone else who reads the code up for confusion, and your program up for bugs.
  2. @selector is not a variable. It's part of a literal expression.

Either define your variable that holds the string in showMessage: instead of myButtonClick, or make it an instance variable and create the string and assign it in init.

Making it an instance variable will also fix the leak you have (you alloc the string but never release it), as long as you release the string in dealloc. See the Memory Management entry in Cocoa Core Competencies for more detail on why your current code is wrong.

I'm also confused as to what myButtonClick is supposed to do. It certainly doesn't click the button—all it does is create it (which you'll find much easier to do in IB). Plus, you don't even put the button into a view; you create it and set it up, and then the method ends.

Peter Hosey