2009-05-10 12 views
120

Sto cercando un metodo per trasformare un NSMutableArray in una stringa. C'è qualcosa di simile a questo metodo di matrice Ruby?Unire una matrice in Objective-C

>> array1 = [1, 2, 3] 
>> array1.join(',') 
=> "1,2,3" 

Cheers!

risposta

259
NSArray *array1 = [NSArray arrayWithObjects:@"1", @"2", @"3", nil]; 
NSString *joinedString = [array1 componentsJoinedByString:@","]; 

componentsJoinedByString: si uniranno ai componenti della matrice dalla stringa specificata e restituire una rappresentazione di stringa della matrice.

17

Il metodo che stai cercando è componentsJoinedByString.

NSArray *a = [NSArray arrayWithObjects:@"1", @"2", @"3", nil];//returns a pointer to NSArray 
NSString *b = [a componentsJoinedByString:@","];//returns a pointer to NSString 
NSLog(@"%@", b); // Will output 1,2,3 
6

NSArray class reference:

NSArray *pathArray = [NSArray arrayWithObjects:@"here", 
    @"be", @"dragons", nil]; 
NSLog(@"%@", 
    [pathArray componentsJoinedByString:@" "]);