我正在尝试通过阅读“学习Objective-C 2.0”来学习Objective-C的基础知识。在一个关于类别的练习中,您被要求通过使用类别向NSString
添加方法。我的简单程序如下。 (应该)取一个字符串,然后颠倒单词的顺序。
主要
#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;
}
接口
#import <Foundation/Foundation.h>
@interface NSString (CatNSString)
- (NSString*) reverseWords:(NSString*)string;
@end
实施
#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
它可以编译,但是程序的行为就像从未调用过该方法一样。如果我在方法中进行NSLog
调用,则不会有任何输出到控制台。谁能看到我不应该做的事情?
答案 0 :(得分:1)
您做错了方法。
这是定义类别的正确方法:
@interface NSString (CatNSString)
-(NSString *)reverse;
@end
@implementation NSString (CatNSString)
-(NSString*)reverse {
// `Self` keyword will refer to your original string, no need to pass it as a parameter
NSArray *words = [self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
return [[[words reverseObjectEnumerator] allObjects] componentsJoinedByString:@" "];
}
@end
并在您的主要代码中,执行以下操作:
NSString *test = @"Dog bites Man";
NSLog(@"%@", [test reverse]);