I'm trying to learn the basics of Objective-C through reading "Learning Objective-C 2.0" Theres an exercise on categories where your asked to add a method to NSString
through use of categories. My simple program is below. it (should) take a string and then reverses the order of the words.
Main
#import <Foundation/Foundation.h>
#import "CatNSString.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSString *test = @"Dog bites Man";
NSString *test1 = nil;
test1 = [test1 reverseWords: test];
NSLog(@"%@ : %@", test, test1);
}
return 0;
}
Interface
#import <Foundation/Foundation.h>
@interface NSString (CatNSString)
- (NSString*) reverseWords:(NSString*)string;
@end
Implementation
#import "CatNSString.h"
@implementation NSString (CatNSString)
- (NSString*) reverseWords: (NSString*) string
{
NSString *stringReturn = nil;
NSArray *arrayString = [string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
stringReturn = [string stringByAppendingString:@"hello"];
for (NSString *word in arrayString)
{
NSString *stringTmp1 = word;
NSString *stringTmp2 = stringReturn;
stringReturn = [stringTmp1 stringByAppendingString:stringTmp2];
NSLog(@"stringTmp1: %@", stringTmp1);
}
return stringReturn;
}
@end
It compiles but the program acts as though the method is never called. If I place a NSLog
call in the method there is no output to the console. Can anyone see what I'm not doing that I should be doing?