2009-04-01 15 views

risposta

26

Entrambe le risposte sono corrette. Se si desidera concatenare più stringhe e numeri interi, utilizzare appendFormat di NSMutableString.

NSMutableString* aString = [NSMutableString stringWithFormat:@"String with one int %d", myInt]; // does not need to be released. Needs to be retained if you need to keep use it after the current function. 
[aString appendFormat:@"... now has another int: %d", myInt]; 
+0

Sto usando qualcosa del genere per la concatenazione di stringhe ma mi dà un avvertimento: "La dichiarazione locale di 'aString' nasconde la variabile di istanza". Cosa potrebbe generare questo errore? – Hari

+1

Non manca un segno di uguale dopo aString? – VagueExplanation

30
[NSString stringWithFormat:@"THIS IS A STRING WITH AN INT: %d", myInt]; 

Questo è in genere come lo faccio.

+1

Controllare anche localizzatoStringWithFormat: e initWithFormat: locale: quando si formatta un numero da utilizzare sullo schermo. –

3
NSString *s = 
    [ 
     [NSString alloc] 
      initWithFormat:@"Concatenate an int %d with a string %@", 
      12, @"My Concatenated String" 
    ]; 

So che probabilmente stai cercando una risposta più breve, ma questo è quello che userei.

+0

È uguale a [NSString stringWithFormat:]? – PlagueHammer

+0

Con questo metodo è necessario rilasciare la stringa quando hai finito con esso. –

+0

@Debajit, in pratica è lo stesso. Dovrai rilasciare la stringa dopo averla usata. –

3

string1, x, sono dichiarati rispettivamente come oggetto stringa e variabile intera. e se si desidera combinare entrambi i valori e aggiungere i valori int a un oggetto stringa e assegnare il risultato a una nuova stringa, procedere come segue.

NSString *[email protected]"Hello"; 

int x=10; 

NSString *string2=[string1 stringByAppendingFormat:@"%d ",x]; 

NSLog(@"string2 is %@",string2); 


//NSLog(@"string2 is %@",string2); is used to check the string2 value at console ; 
-1

Sembra che la vera risposta è no - non esiste un modo facile e breve per concatenare NSStrings con Objective C - nulla di simile ad usare l'operatore '+' in C# e Java.

Problemi correlati