0

I am a mere beginner in iPhone Programming. I have seen this code in a tutorial which I didn't understand what does it means. I am confused about keywords such as titleForState and initWithFormat.

Can anyone help me to understand the meaning and importance of this syntax.

-(IBAction)buttonPressed: (id)sender {
    NSString *title = [sender **titleForState**:UIControlStateNormal];
    NSString *newText = [[NSString alloc] **initWithFormat**:
             @"%@ button pressed.", title];
    statusText.text = newText;//statustext is a label 
    [newText release];
}
Prine
  • 12,192
  • 8
  • 40
  • 59
Techy
  • 2,626
  • 7
  • 41
  • 88
  • Possible duplicate: http://stackoverflow.com/questions/683211/method-syntax-in-objective-c – Prine Nov 14 '12 at 09:54

1 Answers1

1

initwithFormat allows you to modify a string by adding a variable's value to it, you can add as many variables as you like but you have to add the correct symbol for the correct primitive type. Here are some examples

  NSString *thisIsAString = @"String";
  float thisIsAFloat = 13.9f;
  NSString *strFormat = [[NSString alloc] initWithFormat:@"This is a %@, this is a %f float", thisIsAString, thisIsAFloat];
  NSLog(@"%@", strFormat);

This will produce the output This is a String, this is a 13.9f float notice the float and the NSString value have replaced the symbols.

The titleForState is getting the title of an object that has that method. This will return the title for lets say a UIButton that has a title of "Press" for UIControlStateNormal so the value "Press" will be entered into the NSString title. Not though that not everything in sender has the method titleForState the reason this will show up is because sender is a primitive type of id this will cause and error if something is sent that hasn't got titleForState and your app will crash.

Popeye
  • 11,839
  • 9
  • 58
  • 91