Oscar Apeland
Oscar Apeland

Reputation: 6662

stringByAppending string issues

NSString *wantString;
for (id object in [self.wantTypes allKeys]) {
    NSLog(@"object %@",[self.wantTypes objectForKey:object]);
    [wantString stringByAppendingString:[self.wantTypes objectForKey:object]];
}
NSLog(@"%@ wantstring",wantString);

Logs:

Fys1Formel[19004:60b] object Gravitasjon
Fys1Formel[19004:60b] (null) wantstring

Why doesn't appendString work? I tried NSString instead of id

Upvotes: 1

Views: 468

Answers (5)

Miguel Chaves
Miguel Chaves

Reputation: 139

Your problem is that you are not storing the result. And additional you can check if the string you want to add have something inside.

Try to do this way:

NSString *wantString = @""; // init your string empty
NSString *temp = @"";

for (id object in [self.wantTypes allKeys])
{
    temp = [self.wantTypes objectForKey:object];

    if (temp.lenght > 0)
    {
        wantString = [wantString stringByAppendingString:temp];
    }
}

NSLog(@"%@",wantString);

Upvotes: 0

Krishna Kumar
Krishna Kumar

Reputation: 1652

You are calling method to append string but you are not storing or assigning return of that function. SO you need to assign the return of this method:

wantString =  [wantString stringByAppendingString:[self.wantTypes objectForKey:object]];

Upvotes: 4

Greg
Greg

Reputation: 25459

Change it to NSMutableString and allocate it. You also should use appendString, stringByAppendingString return new string, doesn't change your current string.

NSMutableString *wantString = [[NSMutableString alloc] init];
for (id object in [self.wantTypes allKeys]) {
    NSLog(@"object %@",[self.wantTypes objectForKey:object]);
    [wantString appendString:[self.wantTypes objectForKey:object]];
}
NSLog(@"%@ wantstring",wantString);

Upvotes: 2

Evgeniy S
Evgeniy S

Reputation: 1484

Just your wantstring is nil all the time; Try it:

  NSString *wantString;
    for (id object in [self.wantTypes allKeys]) {
        NSLog(@"object %@",[self.wantTypes objectForKey:object]);
         wantString =  [wantString stringByAppendingString:[self.wantTypes objectForKey:object]];
    }
    NSLog(@"%@ wantstring",wantString);

Upvotes: 3

Ali
Ali

Reputation: 643

Use NSMuatableString instead, that's the difference between NSString and NSMutableString (Static vs Dynamic)

Upvotes: 0

Related Questions