2009-06-16 9 views
-1

可能性の重複:方法で上記のコードで
Uibutton eventsuibuttonイベント

-(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..? 
} 

"myButtonclick" 私が設定された1人のNSStringの変数名は "データ" Iでありますそのボタンを押したときにメソッド "showMessage"にその値(YES U PRESSED BUTTON)を取得(そこに表示)したいと思います。

私はこれが@selector変数を使用して行われている知っている..しかし、私はそれが

答えて

4
  1. Stringオブジェクトをどのように行われるか分からないとdata objectsは、二つの異なるものです。文字列変数 "data"の名前を付けないでください。あなた自身と他の誰かがコードを混乱させるように設定しています。プログラムはバグを報告しています。
  2. @selectorは変数ではありません。これはリテラル式の一部です。

showMessage:の代わりmyButtonClick内の文字列を保持しているあなたの変数を定義するか、またはインスタンス変数にすると、文字列を作成し、initでそれを割り当てるのどちらか。

deallocに文字列を解放する限り、インスタンス変数を作成すると、あなたが持っているリーク(文字列alloc)を修正することができます。現在のコードが間違っている理由の詳細については、the Memory Management entry in Cocoa Core Competenciesを参照してください。

また、myButtonClickさんが何をすべきか混乱しています。それは確かにボタンをクリックしません - それはあなたがIBで行う方がずっと簡単です。さらに、ボタンをビューに配置することさえできません。それを作成して設定し、メソッドが終了します。