Why does adding 'dynamic' fix my bad access issues? - 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?

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.

This is from the prerelease Swift / Objective-C interoperability documentation:
Implementing Core Data Managed Object Subclasses
Core Data provides the underlying storage and implementation of properties in subclasses of the NSManagedObject class. Add the #NSManaged attribute before each property definition in your managed object subclass that corresponds to an attribute or relationship in your Core Data model. Like the #dynamic attribute in Objective-C, the #NSManaged attribute informs the Swift compiler that the storage and implementation of a property will be provided at runtime. However, unlike #dynamic, the #NSManaged attribute is available only for Core Data support.
So, because of some of the Objective-C runtime features that Core Data uses under the covers, Swift properties need to be specially annotated.

Related

Swift Core Data Usage in Xcode

I am relatively new to Swift Programming and recently tried out Core Data for the first time. However, I am having a hard time understanding several (for me) strange behaviours I am encountering:
I have create all my entities and their attributes in the ".xcdatamodeld" file. Codegen is on "Manual/None". Some of the attributes are marked a non-optional. Still, when I generate the NSManagedObject Subclass files, I still see them as optional in the "...Properties" files, i.e. having a "?" after the type. Why is that?
Somewhat relating/in contrast to the first bullets, the attributes for some entities do not have the "?", although they are marked as optional. When I try to add the "?", I get an error "Property cannot be marked #NSManaged because its type cannot be represented in Objective-C". Why is that?
When I'm creating the NSManagedObject Subclasses and select some subfolder in my project for them to be created in, they are put at the top of the hierarchy tree, regardless.
What happens if I change information in the "...Class"/"...Properties" files generated by Core Data which would conflict with what is in the ".xcdatamodeld" file. What takes precedence? How are they related?
In general I find there is not much detailed descriptions available on Core Data except introductory things. Would anyone know some good resources on that? Website? Youtube Videos? Books?
Answers:
Creating the subclasses manually treates the optionals not accurately. Check any attribute and remove the question mark in the class if it's non-optional in the model.
Scalar Swift optional types (Int?, Double?, Bool?) cannot be represented in Objective-C. I recommend to declare them as non-optional.
Never mind, it has no effect where the classes are located, the main thing is that the file name is black (valid) in the Project Navigator and the target membership is assigned correctly.
in the Codegen Manual / None case you are responsible that the types in the model match the types in the classes otherwise you could get unexpected behavior. Any change in the class must be done also in the model and vice versa. However you can replace suggested ObjC classes like NSSet or NSDate with native Swift types Set<MyClass> or Date without changing the type in the model.

What are the functional differences between Coredata's CodeGen 'manual/none + create NSManagedObject subclass' vs. 'category/extension'

I've read Subclassing NSManagedObject with swift 3 and Xcode 8 beta and read this great tutorial. Still have questions on some points.
The similarities are:
I can customize both classes however I like.
I can add new attributes or remove or rename attributes. ie for category/extension it will get updated upon a new build (in the derived data), and in case of manual/none it will leave the class file intact and update the extension in the file navigation ie I won't end up with a duplicate file. This is all handled by Xcode because they are marked with a preprocessor #NSManaged
Dumping something like #NSManaged public var name: String? straight into an existing NSManagedObject subclass is not allowed. I tried to do entity.name = "John" but I got the following error: reason: '-[SomeEntity setName:]: unrecognized selector sent to instance 0x60400009b120'. I believe that's reasonable. I think without using the Core Data Model Editor the setter/getter accessor methods are not created.
The differences are:
For Category/Extension you just need to create the class yourself and add any extra functions/properties you need.
For Category/Extension the attributes are created in derived data which is enough. Because you never need to see that file. Its existence is enough to get things working.

And specifically in the context of making changes to your NSManaged properties:
Changing property type, e.g. NSDate to Date is allowed only for Manual/None . Example here
Changing optionality of a type, e.g. String? to String is allowed only for Manual/None. Example here
Changing a property access level, e.g. from public to private is allowed only for Manual/None. Example here
Having that said there is significant difference if I choose Manual/None codegen and but don't select 'create NSManagedObject subclass'. In that case I have start writing all the code myself (subclass from NSManagedObject and write NSManaged for every property)...or if I don't write all that code myself then I can still access/set fields using KVC which is awkward!
In a nutshell I'm just trying to figure out the full extent of capabilities that I can get from using Manual/None.
Question: Aside from the 9 notes which I need to know if I have validated correctly, an important question would be: how does me changing NSDate to Date or optional to non-optional not break the mappings between my NSManagedObject class and my object graph all while changing an NSDate property to String does break!! Does this have something to do with things that have guaranteed casting between Swift and Objective-C ie things that can be casted through as — without ? or !?
To address each of your notes and considering the cases where codegen is set to Manual/None and Category/Extension:
Yes, in either case you can customise the classes however you like (within limits - for example, the class must be a subclass - directly or indirectly - of NSManagedObject).
Correct. You can add, amend or delete attributes in the model editor. In the Category/Extension case, the relevant changes will be made automatically. In the Manual/None case, you can either manually update the Extension (or the class file) or you can redo the "create NSManagedObject subclass" which will update the Extension with the amended attribute details. If you do not do this, Xcode will not recognise the new attribute details and will not provide code completion for them (nor will it successfully compile if you try to override code completion). But unlike what you think this has nothing to do with the properties being marked as #NSManaged.
Correct. Adding an #NSManaged property to the class definition (or Extension) is enough to tell Xcode that the property exists (so you can reference them in code) but does not create the corresponding getter/setter. So your code will crash.
Yes, for Category/Extension just create and tailor the class file as you require.
Yes, for Category/Extension the properties are declared in the automatically created Extension file in Derived Data.
Changing the property definition in any way - from Date to NSDate, or marking it private, or whatever - can only be done in the Manual/None case because the Extension file in Derived Data is overwritten with each new build so any changes are lost.
Ditto
Ditto
Correct. You could write your app without ever creating separate NSManagedObject subclasses (automatically or manually), if you use KVC to access the properties.
As to your final point: you cannot arbitrarily change the type of the property definition: the type specified in the model editor must correspond to the type specified in the property definition. You can switch between optional and non-optional versions of the same type, and you can switch between Date and NSDate etc, but switching from Date to String will not work. I suspect you are correct that this is due to the bridging between Swift value type and the corresponding Objective-C reference type using as. See here.

Realm: Swift `let` property cannot be marked as dynamic

I am using Xcode 7.2, Swift 2.1.1. I have a Realm model object below
class B: Object {
dynamic let lists = List<A>()
}
But the Swift compiler gives me an error saying:
Property cannot be marked as dynamic because its type cannot be represented in Objective-C
I saw Realm's documentation that says:
Realm model properties need the dynamic var attribute in order for these properties to become accessors for the underlying database data.
There are two exceptions to this: List and RealmOptional properties
cannot be declared as dynamic because generic properties cannot be
represented in the Objective-C runtime, which is used for dynamic
dispatch of dynamic properties, and should always be declared with let
But declaring let doesn't seem to solve this case now. What am I missing?
The documentation you quoted includes the following (emphasis mine):
List and RealmOptional properties cannot be declared as dynamic because generic properties cannot be represented in the Objective-C runtime, […], and should always be declared with let.
This means your property should be declared like so:
let lists = List<A>()
The Realm Swift documentation recently gained a property declaration cheatsheet which hopefully clarifies the requirements for the different types of declarations.

Add an extension/method to all objects in Swift

In Objective-C, all objects can be treated as type id, and nearly all objects inherit from NSObject. (Blocks don't, but that's about the only exception.)
Thus it's possible to create an Objective-C category that extends ALL Objective-C objects. (ignoring blocks)
In Objective-C, I created an extension to NSObject that uses associated objects to optionally attach a dictionary to any NSObject. That enabled me to implement methods setAssocValue:forKey: and assocValueForKey: that makes it possible to attach a key/value pair to any NSObject. This is useful in lots of circumstances.
It makes it possible to add stored properties to a category, just for example. You just write a getter/setter that uses the associated value methods to attach a stored object, and away you go.
It also makes it possible to attach values to existing system objects at runtime. You can hang data or blocks of code on buttons, or do whatever you need to do.
I'd like to do the same thing in Swift.
However, Swift does not have a common base class for all objects like Objective-C does. AnyObject and Any are protcols.
Thus,
extension AnyObject
Won't compile.
I'm at a loss as to where to "attach" my setAssocValue:forKey: and assocValueForKey: methods in Swift.
I could create a base class for my extension, but that defeats the point of using an extension. I could make my base object an Objective-C NSObject, but that means all my objects have to be NSObjects, and Swift objects are not NSObjects by default.
(BTW, this question applies to both the Mac OS and iOS platforms)
No. You've pretty much answered your own question--Swift objects don't have a base class, and the only real way to get around it is to inherit from NSObject.

Private property declaration in your class implementation?

Sorry if it's too obvious for you. I'm still learning objetive-c and proper design patterns.
Could you explain me why it is a good idea to declare a property inside #interface in implementation file of a class as a private property? You just can use a local declaration of your type with a class scope, since nobody outside your class would use any getter or setter for this property.
Thanks.
By using the property semantics, you get memory management behavior handled 'for free' by the compiler. Even if your data is private within your class, having the compiler emit correct release/retain/copy saves time and mistakes down the line.
With the modern ARC compiler, this is probably less of an issue now.
When you declare something as #private, usually an instance variable or a property, it became only accessible in methods of the class that declared it. Trying to access it from a subclass results in an error.
I know you didn't asked for this but there is also #protected, when a property is declared like this, it becomes only accessible in methods of the class that declared it and in the methods of any class that inherits from that class.
The source for this info is the best book I know about Objective-C - Learning Objective-C 2.0 by Robert Clair.