PDA

View Full Version : Why doesn't [myArray count] work here??




dantastic
Jan 21, 2011, 10:49 AM
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?

thanks!



dejo
Jan 21, 2011, 10:59 AM
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.

Shawnpk
Jan 21, 2011, 01:10 PM
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?

thanks!

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.

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

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