24

i'm an absolute newbie with objective-c

with this code

NSMutableString *teststring;
[teststring appendString:@"hey"];
NSLog(teststring);

nothing gets displayed in the console.

Surely i'm doing something wrong here... :-)

Apurv
  • 17,116
  • 8
  • 51
  • 67
murze
  • 4,015
  • 8
  • 43
  • 70

5 Answers5

58

You need to create the string first.

NSMutableString *teststring = [[NSMutableString alloc]init];

[teststring appendString:@"hey"];

NSLog(teststring);

Now, it will print.

eric.mitchell
  • 8,817
  • 12
  • 54
  • 92
Apurv
  • 17,116
  • 8
  • 51
  • 67
28

Change first line to

NSMutableString *teststring = [NSMutableString string];
Shmidt
  • 16,436
  • 18
  • 88
  • 136
9

This line

NSMutableString *teststring;

simply establishes a pointer, but does not create anything. Instead, you need to create a new instance of NSMutableString, for example:

NSMutableString *teststring = [[NSMutableString alloc] init];
[teststring appendString:@"hey"];
NSLog("%@", teststring);
PengOne
  • 48,188
  • 17
  • 130
  • 149
5

Sample:

NSMutableString *buffer = [[NSMutableString alloc] init]; // retain count = 1. Because of the "alloc", you have to call a release later

[buffer appendString:@"abc"];
NSLog(@"1 : %@", buffer);
[buffer appendString:@"def"];
NSLog(@"2 : %@", buffer);

[buffer release]; // retain count = 0 => delete object from memory
Sly
  • 2,105
  • 5
  • 22
  • 28
0
NSMutableString *tag = [NSMutableString stringWithString: @"hello <td> this is inside td </td> 000999 <><> ..<. ><> 00000 <td>uuuuu</td> vvvvv <td> this is also inside td </td>"];  
    NSRange open = [tag rangeOfString:@"<"]; 
    while(open.location != NSNotFound) 
    {
        NSRange close = [tag rangeOfString:@">"]; 
        NSRange string = NSMakeRange(open.location, close.location-open.location+1);
        [tag replaceCharactersInRange:string withString:@""];               
        open =  [tag rangeOfString:@"<"];
        NSLog(@"%@",tag);
    }
Dawny33
  • 10,543
  • 21
  • 82
  • 134