I am relatively new in Objective C but not with programming. I was wondering how you can append one NSString onto another. I am making an app in which a user has to finish a basic sentence, and I was wondering how to get the string the user entered and append it onto the current one that is on the screen?
Working with NSString. Instances of the class NSString are immutable – their contents cannot be changed. Once a string has been initialized using NSString, the only way to append text to the string is to create a new NSString object. While doing so, you can append string constants, NSString objects, and other values.
You use it with @"%@%@" to concatenate two strings, @"%@%@%@" to concatenate three strings, but you can put any extra characters inside, print numbers, reorder parameters if you like and so on.
(NSString *) is simply the type of the argument - a string object, which is the NSString class in Cocoa. In Objective-C you're always dealing with object references (pointers), so the "*" indicates that the argument is a reference to an NSString object.
A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior. iOS 2.0+ iPadOS 2.0+ macOS 10.0+ Mac Catalyst 13.0+ tvOS 9.0+ watchOS 2.0+
I think you are looking for stringByAppendingString function of NSString. See the example below.
NSString *errorTag = @"Error: "; NSString *errorString = @"premature end of file."; NSString *errorMessage = [errorTag stringByAppendingString:errorString];
produces the string “Error: premature end of file.”.
This could also be achieved by using a NSMutableString:
NSMutableString *string = [NSMutableString stringWithString:@"String 1"]; [string appendString:@"String 2"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With