简体   繁体   中英

How to properly copy and return a CGFloat

I have this code where I copy my float that I need to remember.

- (void) rememberThisFloatForLater:(CGFloat)floatToRemember {

self.rememberedFloat = &(floatToRemember);

}

And here is self.rememberedFloat in the header file...

@property (assign) CGFloat *rememberedFloat;

My issue is here when I try to return the remembered float. When I return it, I get 6.92867051318e-310 and I should get 3.14159265359 because that is what floatToRemember equals. Where am I going wrong?

- (CGFloat) floatYouShouldRemember {

return *(self.rememberedFloat);
}

CGFloat is a primitive type. It would be very, very, very unusual that you would ever have a property of type CGFloat*. Use CGFloat instead.

Think about what you have been doing: floatToRemember is a method parameter, which is roughly the same as a local variable. You are taking the address of that variable and store it. Then your method returns. Which means the local variable disappears. Which means its address is now utter rubbish. Actually worse than utter rubbish; it is an indeterminate value, and almost any operation using it is undefined behaviour which can crash your program immediately if you are lucky (or can crash your program when a customer uses it, if you are unlucky).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM