2

I am completely new to Objective-C and although i have some experience with java and C#, I just can't get this to work.

My code is:

- (IBAction)btnClickMe_Clicked:(id)sender {
    Label_1.text = (@"some string" + _Label_2.text);
}

I am also curious as to why Label_1 does not need an underscore infront of it, like _Label_2 does?

lnafziger
  • 25,760
  • 8
  • 60
  • 101
Developer
  • 736
  • 7
  • 30
  • 1
    Can you show us the declarations of the outlets? – N_A Jun 25 '13 at 13:46
  • 1
    In the future, when you have two different (unrelated) questions, please ask them as two different questions so that people can focus on one at a time, and people with different areas of expertise can weigh in on the appropriate question. For your second question, see this previously asked (and answered) question: http://stackoverflow.com/q/4142177/937822 – lnafziger Jun 25 '13 at 14:16
  • Objective-C doesn't support operator overloading like c++ – JDS Jun 25 '13 at 14:52

3 Answers3

3

To concatenate strings, you use

Label_1.text = [@"Some string" stringByAppendingString:_Label_2.text];
Cyrille
  • 25,014
  • 12
  • 67
  • 90
  • Your choice of words implies it's the *only* way to concatenate NSStrings. It is not! –  Jun 25 '13 at 14:19
3

You can use %@ to append your additionnals strings with stringWithFormat

Label_1.text = [NSString stringWithFormat: @"Some string %@", _Label_2.text];

More example : Apple - Formatting String Objects

olamarche
  • 445
  • 3
  • 9
0

NSString provides a vast variety of methods for string manipulations. Amongst them are several ways for conatination.

You should get familiar with the factory method stringWithFormat. It is one of the most powerful and especially good at a bit more complex requirements.

In your case:

Label_1.text = [NSString stringWithFormat:@"Some string%@", _Label_2.text);

or

Label_1.text = [NSString stringWithFormat:@"%@g%@", @"Some string", _Label_2.text);

The format string corresponds to the usual standard c printf format string plus the %@ tag which is replaced by any objects description value. So you could have an NSNumber there or even an NSArray or so. However, the description of NSArray, NSDictionary, NSSet etc. may not really be useful for production but come quite handy for debugging. NSLog() uses the same format.

Hermann Klecker
  • 14,039
  • 5
  • 48
  • 71