Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

dantastic

macrumors 6502a
Original poster
Jan 21, 2011
572
678
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!
 
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.
 
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!

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.
 
And you are both right. It was so simple. :p

Thanks! I'll be back for more questions very soon!
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.