这行代码有什么作用?
MyObject *objectOne = (MyObject *)recognizer.view;
我对(MyObject *).
它是否有效地将recognizer.view指针转换为MyObject?
谢谢。
这行代码有什么作用?
MyObject *objectOne = (MyObject *)recognizer.view;
我对(MyObject *).
它是否有效地将recognizer.view指针转换为MyObject?
谢谢。
Yes (MyObject *) is statically casting recognizer.view which is a UIView to MyObject. This allows you to call MyObject specific methods/properties on objectOne. Without the cast the compiler will only allow you to call UIView methods.
This is potentially unsafe because you are assuming that recognizer.view is of type MyObject. Bad things may happen if this assumption was untrue. There is a safer way to do this.
Define a helper method to safely cast for you:
static inline id MySafeCast(Class klass, id obj) {
return [obj isKindOfClass:klass] ? obj : nil;
}
The method will return nil if your assumption about the type is wrong.
// objectOne will be nil if recognizer.view is not a MyObject
MyObject *objectOne = MySafeCast([MyObject class], recognizer.view);
这行代码转换recognizer.view为MyObject类型。这将允许您访问MyObject使用点.语法的属性。
由于 Objective C 是一种动态类型语言,类型转换不如强类型语言重要。MyObject*即使不将变量转换为类型,您也可以使用方括号语法调用方法和访问属性。但是,使用点语法访问属性需要正确的类型。
是的,它将识别器.view 转换为 MyObject 类。