我应用category语法写了一个小程序,但xcode报错.
代码如下
NSString+reverse.h
#import <Cocoa/Cocoa.h>
@interface NSString (reverse) 
-(NSString*)reverse();@end
NSString+reverse.m
#import "NSString+reverse.h"
@implementation NSString(reverse)
-(NSString*)reverse(){
int length=[this length];
NSMutableString* reverse=[[NSString alloc] initWithCapacity:length];
while(length>0){
[reverse appendSting:[NSString stringWithFormat:@"%c",[self characterAtIndex:--length]]]; 
}
return [reverse autorelease];
}
@end
main.m
#import <Foundation/Foundation.h>
#import "NSString+reverse.h"int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];    NSString* string=[[NSString alloc] init];
string=@"hello World";
NSLog(@"the reverse string is : %@",[string reverse]);
    [pool drain];
    return 0;
}

解决方案 »

  1.   

    [NSString alloc] 应该是[NSMutableString alloc]
      

  2.   

    NSMutableString* reverse=[[NSString alloc] initWithCapacity:length];
    改为
    NSMutableString* reverse=[[NSMutableString alloc] initWithCapacity:length];另:
    -(NSString*)reverse();
    这是什么写法?强烈建议不要在oc中写c风格代码,为性能没办法的时候去做纯c的底层实现,-(NSString*)reverse;即可。。否则成函数了。
    注意代码格式。。^^
      

  3.   

    谢谢大家.更改代码后,xcode不报错了.但没有达到预期目标.我是想为NSString添加一个可以反转字符串的方法.但我运行完代码后,并没有得到反转的字符串,反而在控制台中看到一堆莫名奇妙的东西.
    NSString+reverse.h
    #import <Cocoa/Cocoa.h>
    @interface NSString (reverse) 
    -(NSString*)reverse;
    @endNSString+reverse.m
    #import "NSString+reverse.h"
    @implementation NSString(reverse)
    -(NSString*)reverse{
    int length=[self length];
    NSMutableString* reverse=[[NSMutableString alloc] initWithCapacity:length];
    while(length>0){
    [reverse appendSting:[NSString stringWithFormat:@"%c",[self characterAtIndex:--length]]]; 
    }
    return [reverse autorelease];
    }

    @end
    main.m
    #import <Foundation/Foundation.h>
    #import "NSString+reverse.h"int main (int argc, const char * argv[]) {
        NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

        NSString* string=[[NSString alloc] init];
    string=@"hello World";
    NSLog(@"the reverse string is : %@",[string reverse]);

        [pool drain];
        return 0;
    }
      

  4.   

    %c只能处理8bit ASCII字符,characterAtIndex返回的是unichar,应该用%C
      

  5.   

    appendSting 应为 appendFormat