XCode: Insert substring in NSString

If you have to insert characters somewhere in the middle of a NSString e.g. to insert some text in a NSTextfield at cursor position , you have to use NSMutableString.

NSString *myString = @"Cats like to bath!";
NSString *subString = @"don't ";
NSMutableString *txt =[NSMutableString stringWithString:myString];
[txt insertString:subString atIndex:5];
NSLog("%@", txt);

In conjunction with NSTextfield the following code example can be used:

NSString *mySubString = @"don't ";
//getting cursor position of NSTextfield where to insert substring characters
NSUInteger cursorPos = [[[_myTextfield window] fieldEditor:YES  forObject:_myTextfield] selectedRange].location;
//getting NSString-Object of a NSTextfield an converting it to NSMutableString
NSMutableString *txt =[NSMutableString stringWithString:[_myTextfield stringValue]];
//Insert Substring at cursor position
[txt insertString:mySubstring atIndex:cursorPos];
//write back to NSTextfield
[_myTextfield setStringValue:txt];


comments powered by Disqus

Copyright Dunkel & Iwer GbR | Datenschutzerklärung | Impressum