I found a demo snippets which used type casting like this:(int)view.’view’ is a pointer of UIView’s object. I have never known it can be use to cast type. Someone can help me to explain it?
paste code here
- (CGPoint)accelerationForView:(UIView *)view
{
// return
CGPoint accelecration;
// get acceleration
NSValue *pointValue = [self._accelerationsOfSubViews objectForKey:
[NSNumber numberWithInteger:(int)view]];
if (pointValue == nil) {
accelecration = CGPointZero;
}
else {
[pointValue getValue:&accelecration];
}
return accelecration;
}
- (void)willRemoveSubview:(UIView *)subview
{
[self._accelerationsOfSubViews removeObjectForKey:
[NSNumber numberWithInt:(int)subview]];
}
viewis not an object of typeUIView, it’s a pointer of typeUIView*. The code above casts the pointer to an int for the purpose of storing it in aNSNumber, apparently so that it can be used as a key in a dictionary. Since pointers themselves aren’t objects, you can’t use them as dictionary keys. But if you create an instance ofNSNumberfrom the pointer, you can use the resulting object as a key. People do this sort of thing sometimes to keep track of some information that they want to associate with a number of objects (like views) that’s not stored in the objects themselves (like acceleration).As I mention in my comment below, the code here uses
+numberWithInteger:, which is good because that method takes aNSInteger, which will be 32 bits on a 32-bit system and 64 bits on a 64-bit system. However, the author then nullified that good decision by casting toint, which will generally be 32 bits even on a 64-bit system. The cast should really be toNSInteger, like this: