I am dynamically appending and removing substring from NSString –
At specific action I am appending using (I am using comma separator while adding a new string)-
self.selectedString = [self.selectedString length] < 1 ? newSelectedString
: [self.selectedString stringByAppendingFormat:@",%@",newSelectedString];
Removing –
Now this comma is creating problem for me when removing string.
Currently I am using a solution for this as –
self.selectedString = [self.selectedString stringByReplacingOccurrencesOfString:newSelectedString
withString:@""];
NSRange rangeSingleComma = [self.selectedString rangeOfString:@","];
NSRange rangeDoubleComma = [self.selectedString rangeOfString:@",,"];
if (rangeSingleComma.location == [self.selectedString length] - 1) {
self.selectedString = [self.selectedString substringToIndex:[self.selectedString length] - 1];
}
if (rangeSingleComma.location == 0) {
self.selectedString = [self.selectedString substringFromIndex:1];
}
if (rangeDoubleComma.location != NSNotFound) {
self.selectedString = [self.selectedString stringByReplacingOccurrencesOfString:@",,"
withString:@","];
}
But This is a very dirty approach, can any one suggest a good approach for this.
Do you need to store this comma separated list as a string? Instead, try maintaing an NSArray/NSMutableArray of NSString’s. That makes it easy to add or remove any item at will. When you need the comma-separated string representation of the array, just do:
If you’d like to still use your
self.selectedStringproperty, just put the above line of code in a getter method: