0

我是编码和objective-c的新手。我知道有很多类似的问题,但我想知道为什么我的解决方案不起作用。

我为自己创建了一个简单的挑战:反转用户键入的字符串并将textField反转的字符串显示到控制台。但是,此代码不起作用,没有错误,没有通知。

它似乎reversedString只是没有收到任何东西。

- (IBAction)countString:(id)sender {
    NSString *string = [textField stringValue];
    NSUInteger count = [string length];
    [countView setStringValue:[NSString stringWithFormat:@"%@\n%lu", string, (unsigned long)count]];
    // Challenge starts here
    NSMutableString *reversedString = [[NSMutableString alloc] initWithFormat:@""];
    for (NSInteger i = [string length] - 1; i >= 0; i--) {
        NSLog(@"%li", (long)i);
        unichar abc = [string characterAtIndex:i];
        NSString *charString = [NSString stringWithFormat:@"%c", abc];
        [reversedString stringByAppendingString:charString];
    }
    NSLog(@"%@", reversedString);
}
4

2 回答 2

0

对任何对象使用方法:NSString、NSNumber 等。:

NSLog(@"%@",[self reverseObject:@12345]);
NSLog(@"%@",[self reverseObject:@"Hello World"]);

方法:

-(NSString*)reverseObject:(id)string{

string = [NSString stringWithFormat:@"%@",string];
NSMutableString *endString = [NSMutableString new];

while ([string length]!=[endString length]) {
NSRange range = NSMakeRange([string length]-[endString length]-1, 1);
[endString appendString: [string substringWithRange:range]];
}
return endString;
}

日志:

2014-04-16 11:20:25.312 测试[23733:60b] 54321 2014-04-16 11:20:25.313 测试[23733:60b] dlroW olleH

于 2014-04-16T13:10:30.917 回答
0

stringByAppendingString:返回一个新的NSString,并且在您的代码中返回值被忽略,因为您使用的是NSMutableString,替换

[reversedString stringByAppendingString:charString];

[reversedString appendString:charString];
于 2013-09-27T15:33:55.067 回答