zoukankan      html  css  js  c++  java
  • @dynamic关键字

    @dynamic

      You use the@dynamic keyword to tell the compiler that you will fulfill the API contract implied by a property either by providing method implementations directly or at runtime using other mechanisms such as dynamic loading of code or dynamic method resolution. It suppresses the warnings that the compiler would otherwise generate if it can"t find suitable implementations. You should only use it if you know that the methods will be available at runtime.

      The example shown in Listing 5-3 illustrates using @dynamic with a subclass of NSManagedObject.

      Listing 5-3 Using @dynamic with NSManagedObject

      @interface MyClass : NSManagedObject

      {

      }

      @property(nonatomic, retain) NSString *value;

      @end

      @implementation MyClass

      @dynamic value;

      @end

      NSManagedObject is provided by the Core Data framework. A managed object class has a corresponding schema that defines attributes and relationships for the class; at runtime, the Core Data framework generates accessor methods for these as necessary. You therefore typically declare properties for the attributes and relationships, but you don"t have to implement the accessor methods yourself, and shouldn"t ask the compiler to do so. If you just declared the property without providing any implementation, however, the compiler would generate a warning. Using @dynamic suppresses the warning.

      大概的翻译一下:

      @dynamic 就是要来告诉编译器,代码中用@dynamic修饰的属性,其getter和setter方法会在程序运行的时候或者用其他方式动态绑定,以便让编译器通过编译。其主要的作用就是用在NSManageObject对象的属性声明上,由于此类对象的属性一般是从Core Data的属性中生成的,Core Data框架会在程序运行的时候为此类属性生成getter和Setter方法。

    @dynamic与@synthesize的区别在于:

      使用@synthesize,编译器会确实的产生getter和setter方法,而@dynamic仅仅是告诉编译器这两个方法在运行期会有的,无需产生警告。

      假设有这么个场景,a1类,a2类分别继承A类,A类实现某个协议(@protocol),协议中某个属性( somePropety )不想在A中实现,而在a1类,a2类中分别实现。如果A中不写任何代码,编译器就会给出警告:

    “use @synthesize, @dynamic or provide a method implementation"

      这时只要用@dynamic somePropety;

      编译器就不会警告,同时也不会产生任何默认代码。

  • 相关阅读:
    C#GridViewExport帮助类,美化导出
    C#EXCEL 操作类--C#DataToExcel帮助类
    C#EXCEL 操作类--C#ExcelHelper操作类
    VS2010 项目引用了DLL文件,也写了Using,但是编译时提示:未能找到类型或命名空间名称 <转>
    FPGA Verilog HDL 系列实例--------步进电机驱动控制
    C++使用VARIANT实现二维数组的操作
    VS2010+VMWare8+VisualDDK1.5.6 创建并调试你的第一个驱动程序
    USB编程研究之二(常见设备类型的GUID)
    C++——CString用法大全
    C++ 如何有效地使用对话框
  • 原文地址:https://www.cnblogs.com/HMJ-29/p/5996852.html
Copyright © 2011-2022 走看看