2
@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 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

Abizern
  • 146,289
  • 39
  • 203
  • 257
MGD
  • 723
  • 2
  • 11
  • 36

3 Answers3

5

stringByAppendingString: creates new string. Use appendString: instead:

[mutableString appendString:@"hello"]

Yuras
  • 13,856
  • 1
  • 45
  • 58
3

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).

Eiko
  • 25,601
  • 15
  • 56
  • 71
  • Thanks Brother, Problem Solved!, Actually I am new into it and i need good guidance from the experienced people like u :) – MGD Nov 28 '10 at 10:28
1

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.

Community
  • 1
  • 1
zoul
  • 102,279
  • 44
  • 260
  • 354
  • oooopsss yeahhhhh :$ ... m sorry i ve posted such a stupid question btw thanks for help – MGD Nov 28 '10 at 10:30
  • 1
    It’s not a stupid question and there’s nothing wrong with writing a messy code, we have all been through that. (Hell, I *still* write messy code.) Just try to get a little better all the time, that’s all. – zoul Nov 28 '10 at 10:32
  • thank you very much ... ill keep ur valuable advice with me :) – MGD Nov 28 '10 at 16:32