开发者

Have trouble appending to an NSMutableString

@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];
}

Hey Everyone,

i just want to know where I am doing wrong ??? . I tried this code but "mutableString" does not append any value (as开发者_JAVA技巧 value of "len"comes '0' and NSLog doesnt print any value for "mutableString"), though i ve searched on net for the solution, people implemented in the same fashion yet i dont know why my code isnt working.

Thanks in Advance

MGD


stringByAppendingString: creates new string. Use appendString: instead:

[mutableString appendString:@"hello"]


1) Your method names violate the naming conventions: use lower case letters to start with.

2) stringByAppendingString returns a new string as a result and doesn't modify your original. You should use [self.mutableString appendString:@"hello"]; instead.

3) Your init method is leaking. You should use mutableString = [[NSMutableString alloc] init]; and not use the dot syntax, as it will be retained otherwise (and a release would be missing).


Oh God, what a mess. The stringByAppendingString does not change the string, it creates and returns a new one:

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

If you want to change the mutable string itself, use the appendString method:

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

Also, this is a leak:

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

This is best written as:

mutableString = [[NSMutableString alloc] init];

…because using accessors in init and dealloc is not the best idea.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜