Converting between types in Objective-C
Solution 1
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);
Solution 2
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.
Admin
Updated on June 04, 2022Comments
-
Admin almost 2 years
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.
-
David almost 15 yearsI 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.
-
cfischer over 13 yearsI 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)????