Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does adding 'dynamic' fix my bad access issues?

Tags:

swift

I'm having a strange issue that appeared with iOS 8 Beta 5 (this issue did not occur with previous versions).

I tried to create an empty project and try to replicate the issue, but I'm unable to do so, so I'm not quite sure where the issue lies.

What I'm seeing is that attempting to access methods of a custom NSManagedObject subclass results in a strange EXC_BAD_ACCESS error.

For example:

  var titleWithComma: String {        return "\(self.title),"   } 

This method, out of many others, causes this issue when called. However, adding a dynamic keyword before it makes the issue go away:

  dynamic var titleWithComma: String {        return "\(self.title),"   } 

I know I'm not giving enough info, because I honestly don't know how to pinpoint the actual issue, but can anyone explain what is possibly happening, and why adding dynamic might resolve this issue?

like image 282
Snowman Avatar asked Aug 05 '14 14:08

Snowman


1 Answers

From Swift Language Reference (Language Reference > Declarations > Declaration Modifier)

Apply this modifier to any member of a class that can be represented by Objective-C. When you mark a member declaration with the dynamic modifier, access to that member is always dynamically dispatched using the Objective-C runtime. Access to that member is never inlined or devirtualized by the compiler.

Because declarations marked with the dynamic modifier are dispatched using the Objective-C runtime, they’re implicitly marked with the objc attribute.

It means that your property/method can be accessed by Objective-C code or class. Normally it happens when you sub-classing a Swift class of Objective-C base class.

like image 101
Azri Jamil Avatar answered Oct 14 '22 10:10

Azri Jamil