4

I'm starting to develop for the iPhone. I have a beginner-type question, I'm sure:

I have this, which works:

testLabel.text = [NSString stringWithFormat:@"%@ to %@", testLabel.text, newLabelText];

I wish I could use the "+=" operator, but I get a compile error (Invalid operands to binary +, have 'struct NSString *' and 'struct NSString *'):

testLabel.text += [NSString stringWithFormat:@"to %@", newLabelText];

Why can't I do this?

Also, how can I shorten my first snippet of code?

Jeff Meatball Yang
  • 35,999
  • 26
  • 90
  • 121
  • Try to use the solution posted [here](http://stackoverflow.com/questions/510269/how-do-i-concatenate-strings-in-objective-c). – luvieere Oct 05 '09 at 02:16

5 Answers5

5

Think about using an NSMutableString - you can use the appendString: method, as in:

NSMutableString *str = [@"hello" mutableCopy];
[str appendString:@" world!"];
Tim
  • 58,719
  • 19
  • 158
  • 163
5

You can't use the += operator because C and Objective-C do not allow operator overloading. You're trying to use += with two pointer types, which is not allowed -- if the left-hand side of a += expression has a pointer type, then the right-hand side must be of an integral type, and the result is pointer arithmetic, which is not what you want in this case.

Adam Rosenfield
  • 375,615
  • 96
  • 501
  • 581
2

That can't be done because ObjectiveC does not support it, ObjectiveC is a small layer over C.

testLabel.text = [testLabel.text stringByAppendingFormat:@" to %@", newLabelText];
zaph
  • 110,296
  • 20
  • 185
  • 221
1

NSString are NOT mutable (they can't be changed), that's why you can't use +=.

NSMutableString can be changed. You might be able to use them here.

Your code is already pretty minimal. Objective-C is a expressive language so just get used to long, descriptive function and variable names.

ACBurk
  • 4,418
  • 4
  • 33
  • 50
0

try this:

// usage: label.text += "abc"
public func += (a:inout String?, b:String) {
    a = (a ?? "") + b
}

give this custom operator a try:

let label = UILabel()
label.text = "abc"
label.text += "_def"
print(label.text)    // “abc_def”
lochiwei
  • 922
  • 7
  • 12