ios developer tiny share-20160825

来源:互联网 发布:java程序执行顺序 编辑:程序博客网 时间:2024/06/04 20:03

今天讲Objective-C的运行时动态特性。

Objective-C Is a Dynamic Language


As mentioned earlier, you need to use a pointer to keep track of an object in memory. Because of Objective-C’s dynamic nature, it doesn’t matter what specific class type you use for that pointer—the correct method will always be called on the relevant object when you send it a message.

The id type defines a generic object pointer. It’s possible to use id when declaring a variable, but you lose compile-time information about the object.

Consider the following code:

id someObject = @"Hello, World!";[someObject removeAllObjects];

In this case, someObject will point to an NSString instance, but the compiler knows nothing about that instance beyond the fact that it’s some kind of object. The removeAllObjects message is defined by some Cocoa or Cocoa Touch objects (such as NSMutableArray) so the compiler doesn’t complain, even though this code would generate an exception at runtime because an NSString object can’t respond to removeAllObjects.

Rewriting the code to use a static type:

NSString *someObject = @"Hello, World!";[someObject removeAllObjects];

means that the compiler will now generate an error because removeAllObjects is not declared in any public NSString interface that it knows about.

Because the class of an object is determined at runtime, it makes no difference what type you assign a variable when creating or working with an instance. To use the XYZPerson and XYZShoutingPerson classes described earlier in this chapter, you might use the following code:

XYZPerson *firstPerson = [[XYZPerson alloc] init];XYZPerson *secondPerson = [[XYZShoutingPerson alloc] init];[firstPerson sayHello];[secondPerson sayHello];

Although both firstPerson and secondPerson are statically typed as XYZPerson objects, secondPerson will point, at runtime, to an XYZShoutingPerson object. When the sayHello method is called on each object, the correct implementations will be used; for secondPerson, this means the XYZShoutingPerson version.

0 0