Sunday, October 23, 2016

How to insert a character in a NSString Objective C

In Objective C, there are two types of objects one is mutable another one is immutable. If you have to change value of any object you need to declare it as mutable. According to the Apple document,
the value of any immutable object remains same throughout it's life. So if you need to edit the NSString then you have to convert it into NSMutableString first. After that you can use the delegate method it to edit that string.

Suppose, you got (may be from Database or Server) a string like "This book is written by Saddaf Afrin". Now you need to add new line after "written" and "by". In this case you have to use this NSMutableString and it's delegate methods. The situation I have mentioned here, it can be manage by following snippet.
   NSString *string = @"This book is written by Saddaf Afrin";

   NSMutableString *mutableString = [NSMutableString stringWithString:string];
   NSLog(@"The old string %@",mutableString);
   [mutableString insertString:@"\n" atIndex:21];
   [mutableString insertString:@"\n" atIndex:25];

   NSLog(@"The new string %@",mutableString);

And the output will look like Image 1

Image 1: Output After and Before using NSMutableString.

No comments:

Post a Comment