Why doesn't [myArray count] work here??

Discussion in 'iOS Programming' started by dantastic, Jan 21, 2011.

  1. dantastic macrumors 6502a


    Jan 21, 2011
    Hi all, I'm just learning Objective-c from a Java background.

    I am trying to get the middle index of an array in Java it would be something like
    int middleOfArray = myArray.length / 2;

    (ok, that's not entirely valid but you get the point)

    In objective c I'm trying the following:

    	NSLog(@"Creating Array");
    	NSArray *dummy = [NSArray arrayWithObjects:@"a",@"b",@"c",@"d",@"e",@"f",@"g",nil];
    	NSLog(@"Array Created");
    	int middle = [dummy count] / 2;
    	NSLog(@"array middle: %@", middle);
    This compile just fine but during runtime my app crashes and all I've got is:
    2011-01-21 16:37:18.220 Pickers[5321:207] Creating Array
    2011-01-21 16:37:18.220 Pickers[5321:207] Array Created
    I realize that the count return a NSUInteger but from my googling the above should work.

    I have tried to add @try-@catch blocks but I'm not understanding this. Can anyone help me understand where I'm going wrong?

  2. dejo Moderator


    Staff Member

    Sep 2, 2004
    The Centennial State
    Turn on Run > Stop on Objective-C Exceptions. Then bring up the debugger when it stops. You'll see the problem lies in your final NSLog call.
  3. Shawnpk macrumors 6502

    Jan 13, 2011
    Los Angeles, CA
    You set middle as an int, but you are asking for an object in your last NSLog call. Try changing it to %i or %d. Keep in mind that this is going to give you a number back and not the actual letter in the middle of the array.
  4. dantastic thread starter macrumors 6502a


    Jan 21, 2011
    And you are both right. It was so simple. :p

    Thanks! I'll be back for more questions very soon!

Share This Page