2010-11-28 56 views
1
@interface MainView : UIView { 
    NSMutableString *mutableString; 
} 
@property (nonatomic, retain) NSMutableString *mutableString; 
@end 

@implementation MainView 
@synthesize mutableString; 

-(void) InitFunc { 
    self.mutableString=[[NSMutableString alloc] init]; 
} 

-(void) AppendFunc:(*NString) alpha { 
    [self.mutableString stringByAppendingString:@"hello"]; 
    NSLog(@"the appended String is: %@",self.mutableString); 
    int len=[self.mutableString length]; 
} 

嘿大家,有麻烦追加到的NSMutableString

我只是想知道我做错了??? 。我试过这段代码,但“mutableString”不会附加任何值(因为“len”的值为'0',NSLog不会为“mutableString”打印任何值),尽管我已经在网上搜索解决方案,同样的时尚,但我不知道为什么我的代码不工作。

由于提前

MGD

回答

5

stringByAppendingString:创建新的字符串。使用appendString:来代替:

[mutableString appendString:@ “你好”]

+0

THANKSSSSSS正确答案 – MGD 2010-11-28 10:30:57

1

哦,上帝,什么乱七八糟的。该stringByAppendingString不改变字符串,创建并返回一个新问题:

// Sets str2 to “hello, world”, does not change str1. 
NSMutableString *str1 = [NSMutableString stringWithString:@"hello, "]; 
NSString *str2 = [str1 stringByAppendingString:@"world"]; 

如果你想改变可变的字符串本身,使用appendString方法:

// Does not return anything, changes str1 in place. 
[str1 appendString:@"world"]; 

此外,这是一个泄漏:

self.mutableString = [[NSMutableString alloc] init]; 

这是最好写为:

mutableString = [[NSMutableString alloc] init]; 

...因为在initdealloc中使用访问器is not the best idea

+0

oooopsss yeahhhhh:$ ...对不起,我已经发布这样一个愚蠢的问题顺便说一句感谢的帮助 – MGD 2010-11-28 10:30:19

+1

这不是一个愚蠢的问题并没有什么错写乱码,我们已全部通过。 (地狱,我*仍然*写乱码。)只是试图让所有的时间好一点,就这些。 – zoul 2010-11-28 10:32:49

3

1)您的方法名称违反了命名约定:以小写字母开头。

2)stringByAppendingString作为结果返回一个新的字符串,并不会修改您的原始。您应该使用[self.mutableString appendString:@"hello"];

3)您的init方法正在泄漏。您应该使用mutableString = [[NSMutableString alloc] init];而不是使用点语法,否则将会编辑retain(并且将会丢失release)。