2

这行代码有什么作用?

MyObject *objectOne = (MyObject *)recognizer.view;

我对(MyObject *).

它是否有效地将recognizer.view指针转换为MyObject

谢谢。

4

3 回答 3

3

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);
于 2013-06-04T18:05:30.653 回答
2

这行代码转换recognizer.viewMyObject类型。这将允许您访问MyObject使用点.语法的属性。

由于 Objective C 是一种动态类型语言,类型转换不如强类型语言重要。MyObject*即使不将变量转换为类型,您也可以使用方括号语法调用方法和访问属性。但是,使用点语法访问属性需要正确的类型。

于 2013-06-04T18:06:20.223 回答
1

是的,它将识别器.view 转换为 MyObject 类。

于 2013-06-04T18:05:37.423 回答