Reputation: 1934
How can I check if an NSMutableArray contains an object which contains certain text? Then, if there is one piece of text which has been found, it will replace it with another bit of text.
Thanks
Upvotes: 2
Views: 2491
Reputation: 11439
You can either iterate on your array, do the checking on each object and then replace if necessary.
Or you could use something fancier with :
- (void)makeObjectsPerformSelector:(SEL)aSelector withObject:(id)anObject
I havent tried it but you could create a method in your object that takes a dictionary, or an array with first element being the text to compare and second element the text to replace :
- (void) replaceTextWithParameters:(NSArray*)parameters {
if([self.yourText isEqualToString:[parameters objectAtIndex:0]) {
self.yourText = [parameters objectAtIndex:1];
}
}
Then you would only have to call :
NSArray *parameterArray = [NSArray arrayWithObjects:@"Text to search", @"replacementText", nil];
[yourArray makeObjectsPerformSelector:@selector(replaceTextWithParameters:) withObject:parameterArray];
It would be a lot faster at run time than looping on each element of your array (especially if you have many elements)
Upvotes: -1
Reputation: 907
You can perform a check inside a for loop for all objects in the NSMutableArray , use [object rangeOfString:@"text"] for check the range.
Upvotes: 1
Reputation: 163238
Something like this should work:
@interface NSMutableArray (JRAdditions)
- (void) replaceStringObjectsContainingString:(NSString *) str withString:(NSString *) newString;
@end
@implementation NSMutableArray (JRAdditions)
- (void) replaceStringObjectsContainingString:(NSString *) str withString:(NSString *) newString {
for(unsigned i = 0; i < [self count]; ++i) {
id obj = [self objectAtIndex:i];
if(![obj isKindOfClass:[NSString class]]) continue;
NSString *replaced = [str stringByReplacingOccurrencesOfString:str withString:newString];
[self replaceObjectAtIndex:i withObject:replaced];
}
}
@end
You'd then use it as such:
NSMutableArray *array = ...;
[array replaceStringObjectsContainingString:@"blah" withString:@"foo"];
Upvotes: 2