views:

2108

answers:

2

Being a starting Objective-C developer, and not having the patience to actually do some studying, rather than just diving into things, I ran into the following:

I have a CGFloat, and I want to divide it by something, and use the result as an NSInteger.

Example:

CGPoint p = scrollView.contentOffset; //where p is a CGFloat by nature
NSInteger * myIndex = p.x/468.0;

While compiling, I get the error: "Incompatible types in initialization". I guess that's because of the mismatch between the CGFloat and the NSInteger.

What should I know to get out of this? Sorry for bothering you.

+4  A: 

Two problems. You're using a NSInteger pointer (NSInteger *myIndex). And you'll need a cast to go from float to int. Like so:

NSInteger myIndex = (int)(p.x / 468.0);
David
Thanks David! That whole pointer part still scares me a bit. So far, I've been able to avoid it, but I'll now HAVE to start reading Kochan.
I haven't done a lot of Objective C, but in my limited experience you don't have to use many C-style pointers (using the * with a primitive type like int). Objective C objects are handled pretty nicely.
David
+4  A: 

NSInteger is not an actual object type. It is a typedef for a primitive integer type. Remove the * and your example should work. As it is now, you're trying to assign the result of your math as a pointer and you're getting that error message.

jkf
I got into similar troubles for thinking that NSInteger was a subclass of NSNumber. Anybody knows why on Earth someone created the NSInteger typedef (besides wreaking havoc, misery and confusion among newbies)????
Fernando