@dynamic關鍵字的作用

先引用一段apple的解釋:

  @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僅僅是告訴編譯器這兩個方法在運行期會有的,無需產生警告。

假設有這麼個場景,B類,C類分別繼承A類,A類實現某個協議(@protocol),協議中某個屬性( somePropety )我不想在A中實現,而在B類,C類中分別實現。如果A中不寫任何代碼,編譯器就會給出警告:

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

這時你給用@dynamic somePropety; 編譯器就不會警告,同時也不會產生任何默認代碼。



發佈了13 篇原創文章 · 獲贊 12 · 訪問量 35萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章