`
blessdyb
  • 浏览: 235720 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

The secret about Objective-C magic Data-Type id

阅读更多

The id data type is, in a sense, a generic data type. It can stand in for Objective-C basic data types (e.g., various types of numbers) or Cocoa Touch objects (e.g., buttons, arrays, and views). In fact, a variable defined as an id data type can even change the type of data it holds during the execution of a method. This flexibility is a hallmark of Objective-C, called dynamic typing (also known as late binding). The idea behind dynamic typing is that a variable doesn’t need to be prewired for only one data type;instead the data type (a class) is assigned at runtime, and the system keeps track of the type as needed (and thus knows to which class it should send messages).
As an illustration of dynamic typing and the id data type, consider an app that defines three very different classes named Leg, Glass, and Meeting. Each class has a method named break, which performs a class-specific breaking action on an instance of that class. As the app runs, a variable of type id could contain an instance of any one of those classes, depending on user interaction or another situation. But when a statement sends the break message to the variable, the actual class of the variable at that instant determines which method executes. Importantly, the compiler can’t know whether a class assigned to the variable has a break method defined for it, because at compile time the class of the variable is indeterminate.

Before you draw the conclusion that you can simply adopt the id data type for everything and treat all Objective-C variables as loosely typed JavaScript variables, hold your horses! The compiler will let potential data type incompatibilities slide by if you are sloppy with typing. Errors will occur at runtime and conceivably generate crashes that can be challenging to repair even with the Xcode debugger. You are often better off finding data type inconsistencies at compile time rather than at runtime. The Xcode compiler supplies many clues (albeit not all of them immediately clear to newcomers) about data type issues. It’s true that accurately typing your variables and methods may be frustrating to work with at first—you’ll feel as though you’re doing a lot of the work the compiler should be doing—but the code will be easier to maintain over time.
Despite these cautions, don’t be afraid of dynamic typing—Cocoa Touch frameworks use it extensively. It will just take some time working in Objective-C before you recognize places where dynamic typing can contribute to your code’s flexibility.

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics