myString的结果是错误的

时间:2015-04-28 13:38:07

标签: objective-c

#import <Foundation/Foundation.h>

@interface Person : NSObject

/* method declaration*/
+(NSString *)setMyname:(NSString *)name Sex:(NSString *)sex Age:(int)age;

@end

@implementation Person

+(NSString *)setMyname:(NSString *)name Sex:(NSString *)sex Age:(int)age
{
    NSString* string=[NSString alloc];
    string=[NSString stringWithFormat:@"My name is %@ and sex is %@ and age is %d",name,sex,age];
    return string;
}

@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSString* myString =[NSString new];
        myString=[Person setMyname:@"Yyx" Sex:@"Male" Age:21];
        NSLog(@"%@",myString);
    }
    return 0;
}

字符串的结果应该是“我的名字是XXX”。但程序没有结束友好,字符串的值是     string NSString * 0x7fff7a38c830 0x00007fff7a38c830。 断点位于NSString* string=[NSString alloc];

的行

1 个答案:

答案 0 :(得分:1)

只需执行以下操作:

NSString* string = [NSString stringWithFormat:@"My name is %@ and sex is %@ and age is %d",name,sex,age];

stringWithFormat:方法为您分配并构建新字符串。

然后这样称呼:

NSString* myString=[Person setMyname:@"Yyx" Sex:@"Male" Age:21];