3
NSLog(@"%d",[annotations count]);

The above code is used with an NSMutableArray named 'annotations'.

My question is... what does this code do exactly?

I know NSLog outputs text, and its saying annotations count.. so I am thinking that it outputs the amounts of elements in the annotations array.

Am I correct?

Simagen
  • 409
  • 2
  • 8
  • 18

3 Answers3

3

You could have just run the code to test this, but yes this command outputs to NSLog the count of the array named "annotations". For example if the array contains objects and indexes 0,1,2,3, and 4 the array's count will be 5.

NSArray * array = [NSArray arrayWithObjects:@"zero", @"one", @"two", @"three", @"four", nil];
NSLog(@"Number of items in my array is: %d", [array count]);//this will return (5)

For more details, see this post: Size of an NSArray

Community
  • 1
  • 1
Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281
2

Yes, you are correct exactly. NSLog prints text to the console window, and the count function of an array outputs the number of elements in that array.

NSLog prints text in a special way; wherever there is a %i, %d, %f, %@, etc, it replaces that symbol with a passed variable. So if I typed:

NSLog(@"Hi my name is %@. I am %i years old.", @"Sarah", 12);

The console would print:

Hi, my name is Sarah.  I am 12 years old.

So in your example, if annotations has 10 elements, 10 will simply be printed to the console. This can get confusing if you simply print a bunch of numbers though! So using NSLog's flexibility, it would be easier to read your log output if you did this:

NSLog(@"Elements in annotations array: %d", [annotations count]);

Then this would be printed to your console:

Elements in annotations array: 10

Which might be more helpful when reading back through your logs!

WendiKidd
  • 4,333
  • 4
  • 33
  • 50
  • In your first example, you are expecting a string object but supplying a C-style character array (c-string). Fix that by prefixing the Sarah-string by an AT-symbol. – Till Sep 03 '12 at 19:11
  • @Till Meep, sorry! Thanks for catching the typo! – WendiKidd Sep 06 '12 at 23:48
1

Yes it will simply display the count of objects in the array

Darren
  • 10,182
  • 20
  • 95
  • 162