so im trying to add new method for testing using Category from NSString
, but some how i must declared like this with following step:
Create Category from NSString
with name StringExtension
so it will be NSString+StringExtension
, after that i declared my own methos that return type is String
so after i define in NSString+StringExtension
@interface
and @implementation
, i tried in my viewController to called it, but first i import the class NSString+StringExtension
after that i do like this
NSString *testString = @"as d a s d";
NSLog(@"===== %@", [testString removeWhiteSpaceStringWithString:testString]);
and it says
No visible @interface for 'NSString' declares the selector 'removeWhiteSpaceStringWithString:'
the question is, why it cannot use like that? i already search and see tutorial doing like that and its possible, but why i'm not able to do that?
so i found this way, but i don't know is this the correct code to use?
NSLog(@"===== %@", [[testString class] removeWhiteSpaceStringWithString:testString]);
anyone have the same case like i am?
Based upon what you have shared with us, it would appear that you defined a class method (with +
). It should be an instance method (with -
) and then you don’t need the parameter, either. You can simply reference self
.
For example:
// NSString+Whitespace.h
@import Foundation;
NS_ASSUME_NONNULL_BEGIN
@interface NSString (Whitespace)
- (NSString *)stringByRemovingWhitespace;
@end
NS_ASSUME_NONNULL_END
And
// NSString+Whitespace.m
#import "NSString+Whitespace.h"
@implementation NSString (Whitespace)
- (NSString *)stringByRemovingWhitespace {
return [self stringByReplacingOccurrencesOfString:@"\\s+"
withString:@""
options:NSRegularExpressionSearch
range:NSMakeRange(0, self.length)];
}
@end
Then you can do:
NSString *testString = @"as d a s d";
NSLog(@"===== %@", [testString stringByRemovingWhitespace]); // ===== asdasd
Obviously, do whatever you want in your implementation, but it illustrates the idea, that you want an instance method and you do not need to pass the string again as a parameter.