NSString category issues

Hello,

I'm having some NSString category issues with alternate NSString types. Here is an example. I have a simple category as one can see here and In this case, I get a error "Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFConstantString containsString:ignoringCase:]: unrecognized selector sent to instance 0x100098070'".


I have got similar errors with NSTaggedPointerString on the "trim" function.


Has nayone seen this, and how have you addressed it?

Thanks!


// NSString Category

@interface NSString (StringHelper)
- (NSString *)trim;
- (BOOL)containsString:(NSString *)aString ignoringCase:(BOOL)flag
@end


@implementation NSString (StringHelper)

-(NSString *)trim
{
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

- (BOOL)containsString:(NSString *)aString ignoringCase:(BOOL)flag
{
    unsigned mask = (flag ? NSCaseInsensitiveSearch : 0);
    NSRange range = [self rangeOfString:aString options:mask];
    return (range.length > 0);
}

@end



Test Code

// Test Code that fails ...
NSString *b = @"Bob";
if ([b containsString:@"m" ignoringCase:YES]) {
  NSLog(@"Contains");
} else {
  NSLog(@"NO");
}

Replies

There is a syntax error in your header. You need a semicolon at the end of the containsString:ignoringCase: method definition.

No, it's correct in my file. I must have deleted it while cleaning up this when I pasted it in.

When I added the semicolon, it worked fine.


Are you importing the header where the category is defined in all the source files where it is used?

So, Ive narrowed it down a bit more. My categories are in my static library. If I pull them out of it and add add it to the project specfically it works fine.


This used to work just fine in Xcode 8, these categories have not changed and neither has the static library in a couple of years.

It used to be necessary to specify the "-ObjC" linker option for static libraries that contained Obj-C code, otherwise the linker would eliminate some classes as "dead" (unreachable) code:


https://developer.apple.com/library/archive/qa/qa1490/_index.html


Take care, though, that Xcode behavior may have changed a bit over the years, so this information might not be exactly up to date.

I suspect that QuinceyMorris’s most recent answer will solve your issue, but I have another concern. The methods you’re adding to

NSString
have very obvious names, which raises the possibility that they might collide with methods added by others (either added by the system frameworks in the future, or by third-party libraries you’re using). I strongly recommend that you tweak your method names to be more unique.

See Avoid Category Method Name Clashes for more details on this issue.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"