1

I have array:

NSArray *array = [NSArray arrayWithObjects:@"One",@"Second",@"Third", nil];

I want to get this code result in console:

[One]
background = 0,

[Second]
background = 1,

[Third]
background = 2,

I try to use this code to do it:

Int n = 0;
for (; n < 3; n++)
{

NSArray *array = [NSArray arrayWithObjects:@"One",@"Second",@"Third", nil];
NSString *stringFromArray = [array componentsJoinedByString:@"], background = %i ["];
NSLog (@"%@",stringFromArray);
}

How to solve the problem?

2 Answers2

3

If you want to build a string with that content, rather than just displaying it to the console, use code like this:

NSArray *array = [NSArray arrayWithObjects:@"One",@"Second",@"Third", nil];

NSMutableString *output = [NSMutableString new];
for (int index = 0; index < array.count; index++) {
  [output appendFormat: @"[%@]\nbackground = %d,\n\n", array[index], index];
}

And to display it without the NSLog headers, convert it to a string and use printf():

const char *cString = [output cStringUsingEncoding: NSASCIIStringEncoding];
printf("%s", cString);

Objective-C's string handling is generally better than C's, so it's not uncommon to do string work with NSString objects and then convert to C strings at the end.

If you do this a lot in a big program you can write a printString() function that takes an NSString as input, converts it to a C string, and displays it with printf()

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • I understand this is not welcomed by the community. But could you please help with this problem. I just don't know what to do. Thanks! - https://stackoverflow.com/questions/69851479/audio-files-wont-play-with-airpods-pro-on-ios-15 – user Nov 12 '21 at 20:35
1

How about this?

for (NSString *each in array) {
    NSLog(@"[%@]\nbackground = %d", each, [array indexOfObject:each]);
}
kirander
  • 2,202
  • 20
  • 18
  • Thank you. It is works! But what if I want this result `[@"One"]`? –  Oct 29 '17 at 11:16
  • Change it like this NSLog(@"[@\"%@\"]\nbackground = %d", each, [array indexOfObject:each]); – kirander Oct 29 '17 at 11:26
  • 1
    And if I want to remove time in console `2017-10-29 14:37:26` I should use `printf`? But if I use `printf` I get issue `Invalid conversion specifier '@'` –  Oct 29 '17 at 12:12
  • See my answer about avoiding the timestamps from NSLog. – Duncan C Oct 29 '17 at 12:53