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];
}
initwithFormatallows 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 examplesThis will produce the output
This is a String, this is a 13.9f floatnotice thefloatand theNSStringvalue have replaced the symbols.The
titleForStateis 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” forUIControlStateNormalso the value “Press” will be entered into theNSStringtitle. Not though that not everything in sender has the methodtitleForStatethe reason this will show up is because sender is a primitive type ofidthis will cause and error if something is sent that hasn’t gottitleForStateand your app will crash.