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

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

  1. macrumors 6502

    dantastic

    Joined:
    Jan 21, 2011
    #1
    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:

    Code:
    	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:
    Code:
    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?

    thanks!
     
  2. Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #2
    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. macrumors 6502

    Joined:
    Jan 13, 2011
    Location:
    Los Angeles, CA
    #3
    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. thread starter macrumors 6502

    dantastic

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

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

Share This Page