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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值