Asaf Nevo Asaf Nevo - 1 year ago 117
iOS Question

NSString containsString crashes

I'm trying to filter an array according to one of it's string fields.

Both nameLower and filterLower has NSString value inside, and yet i keep getting:

__NSCFString containsString:]: unrecognized selector sent to instance 0x7f876b79e160

-(void) filterFriendsArray:(NSString*)filter {
[_filteredFriendsArray removeAllObjects];
for (FacebookUser* user in _friendsArray)
NSString* nameLower = [ lowercaseString];
NSString* filterLower = [filter lowercaseString];
if ([nameLower containsString:filterLower])
[_filteredFriendsArray addObject:user];
_displayedFriendsArray = _filteredFriendsArray;

Answer Source

If you want your code to work on iOS 7 as well as iOS 8 you should use one of the rangeOfString calls instead. Basically if the range returned has a length of zero, the substring is not there.

/* These methods return length==0 if the target string is not found. So, to check for containment: ([str rangeOfString:@"target"].length > 0).  Note that the length of the range returned by these methods might be different than the length of the target string, due composed characters and such.
- (NSRange)rangeOfString:(NSString *)aString;
- (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask;
- (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask range:(NSRange)searchRange;
- (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask range:(NSRange)searchRange locale:(NSLocale *)locale NS_AVAILABLE(10_5, 2_0);

Obviously it's trivial to implement containsString yourself in a category using rangeOfString:

@implementation NSString (Contains)

- (BOOL)myContainsString:(NSString*)other {
  NSRange range = [self rangeOfString:other];
  return range.length != 0;