How can I use a Transformable attribute as its actual type in a NSManagedObject subclass? - cocoa

Just starting a project. The data-model file has one entity, which has a single attribute that is Transformable. It's supposed to be a NS/CGRect. I had Xcode create corresponding NSManagedObject subclass files. For "MyThing.swift", I got:
import Foundation
import CoreData
class MyThing: NSManagedObject {
// Insert code here to add functionality to your managed object subclass
}
And I got a "MyThing+CoreDataProperties.swift":
import Foundation
import CoreData
extension MyThing {
#NSManaged var myBounds: NSObject?
}
I want the property to be an actual CGRect, so I need a NSData <-> NSValue <-> NSRect conversion chain. I already have "NSKeyedUnarchiveFromDataTransformer" as the Name under the Attribute Type in Interface Builder. What do I add (and/or change) to pass CGRect values around?
Or do I not do this, and just pass NSValue-wrapped CGRects around instead? (I hope that CoreData will take care of any NSData <-> NSValue conversions.)

As long as your transformable type complies to NSCoding, Core Data will take care of the rest for you. I've used NSAttributedString in my NSManagedObjects, and only changed the CoreData provided id-type that was generated at runtime.
If you want to have a property of your own type, i.e. MyAwesomeObject, then make sure you implement initWithCoder: and encodeWithCoder:.
So, for your case, in order to store CGRects with CoreData, you would need to wrap them in a class that implements the above mentioned methods. This is because CGRect doesn't comply to the NSCoding protocol, and thus cannot be stored directly as a transformable attribute.
Your other option is of course to store x,y,width,height as properties, and either have a transient property wich you compute in awakeFromFetch and awakeFromInsert or just a convenience method.

Because CGRect is not a class but struct i would suggest creating another property which will access the raw variable with proper conversions. And then use only that property.
class MyThing {
var boundsValue : NSValue?
}
extension MyThing {
var bounds : CGRect {
get {
if let value = boundsValue {
value.CGRectValue()
}
return CGRectNull
}
set {
boundsValue = NSValue(CGRect: newValue)
}
}
}

Related

How to apply NSCoding to a class?

I have the following class. When I try to add it to NSUserDefaults like this:
let testClass = TestClass()
testClass.Property1 = 22.3
NSUserDefaults.standardUserDefaults().setObject(testClass, forKey: "object1")
I get an error:
'NSInvalidArgumentException', reason: 'Attempt to insert non-property
list object for key object1'
class TestClass: NSObject, NSCoding {
var Property1:Double?
override init() {
super.init()
}
required init?(coder aDecoder: NSCoder) {
if let priceCoded = aDecoder.decodeObjectForKey("Property1") as? Double {
self.Property1 = priceCoded
}
}
func encodeWithCoder(aCoder: NSCoder){
if let priceEncoded = self.Property1 {
aCoder.encodeObject(priceEncoded, forKey: "Property1")
}
}
}
Any idea what I'm doing wrong?
Any idea what I'm doing wrong?
Yes. Not to state the obvious, but "attempt to insert non-property list object" pretty much covers it. The kinds of objects you can insert into the defaults system is limited to property-list types: NSString, NSDate, NSNumber, NSData, and collections NSArray and NSDictionary. You're apparently trying to insert some other kind of object, thus the error.
If you want to store some other kind of object, you'll need to somehow transform it into one of the supported types. You're on the right track -- the usual way to do that is to serialize the object using NSKeyedArchiver, which can store objects that adopt the NSCoding protocol. The idea is that you create a keyed archiver, use it to serialize the object(s) in question, and get back an instance of NSData which you can then store. To get the object back, you do the opposite: use a NSKeyedUnarchiver to deserialize the data object back into the original object.
It looks like you were expecting NSUserDefaults to serialize NSCoding-compliant objects for you, but that doesn't happen -- you need to do it yourself.
There are plenty of examples around, but the usual place to look for this would be the Archives and Serializations Programming Guide. Specifically, check out the "Creating and Extracting Archives" section for sample code. Here's a piece of the relevant example for serializing:
NSMutableData *data = [NSMutableData data];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:aPerson forKey:ASCPersonKey];
[archiver finishEncoding];
Remember that in order to serialize an object this way, that object has to be an instance of a class that adopts the NSCoding protocol. The same document explains how to implement the necessary NSCoding methods, and there must be dozens of questions about it here on SO as well.

NSView with a KVC property in Swift

I have a custom NSView class defined as:
class MyView: NSView
{
var someText: NSString
override func didChangeValueForKey(key: String)
{
println( key )
super.didChangeValueForKey( key )
}
// other stuff
}
What I want to be able to do is from outside of this class change the value of someText and have didChangeValueForKey notice that someText has changed so I can, for example, set needsDisplay to true for the view and do some other work.
How an I do this?
Are you sure you need KVC for this? KVC works fine in Swift, but there’s an easier way:
var SomeText: NSString {
didSet {
// do some work every time SomeText is set
}
}
There is no KVC mechanism for this because this isn't what KVC is for.
In Objective-C, you would implement the setter explicitly (or override if the property is originally from a superclass) and do your work there.
In Swift, the proper approach is the didSet mechanism.
didChangeValueForKey() is not part of KVC, it's part of KVO (Key-Value Observing). It is not intended to be overridden. It's intended to be called when one is implementing manual change notification (as a pair with willChangeValueForKey()).
More importantly, though, there's no reason to believe that it will be called at all for a property which is not being observed by anything. KVO swizzles the class in order to hook into the setters and other mutating accessors for those properties which are actually being observed. When such a property is changed (and supports automatic change notification), KVO calls willChangeValueForKey() and didChangeValueForKey() automatically. But for non-observed properties, those methods are not called.
Finally, in some cases, such as the indexed collection mutation accessors, KVO will use different change notification methods, such as willChange(_:valuesAtIndexes:forKey:) and didChange(_:valuesAtIndexes:forKey:).
If you really don't want to use didSet for some reason, you would use KVO to observe self for changes in the someText property and handle changes in observeValueForKeyPath(_:ofObject:change:context:). But this is a bad, clumsy, error-prone, inefficient way of doing a simple thing.
KVO and didSet are not mutually exclusive:
import Foundation
class C: NSObject {
dynamic var someText: String = "" {
didSet {
print("changed to \(someText)")
}
}
}
let c = C()
c.someText = "hi" // prints "changed to hi"
class Observer: NSObject {
init(_ c: C) {
super.init()
c.addObserver(self, forKeyPath: "someText", options: [], context: nil)
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
print("observed change to \(object!.valueForKeyPath(keyPath!))")
}
}
let o = Observer(c)
c.someText = "test" // prints "changed to test" and "observed change to test"
I would add to Jaanus's answer that to make the property KVC compliant, you should declare it as dynamic var someText: NSString.
But if you don't need all the bells and whistles oh KVC, didSet is the way to go.
Update
As for didChangeValueForKey: – it is intended for the opposite, for you to notify value for key has changed (if it is not due to one of the cases covered by Foundation). You should use addObserver(_:forKeyPath:options:context:) and override observeValueForKeyPath(_:ofObject:change:context:) to be notified of changes.
Alternatively you can use one of many 3rd party solutions such as ReactiveCococa or Facebook's KVOController

Adopting NSTextFinderBarContainer protocol in Swift forces variable initialization despite header comment

I have an NSView subclass that implements the NSTextFinderBarContainer protocol. Part of the NSTextFinderBarContainer protocol is implementing
var findBarView: NSView { get set }
However the comment above this property in the original Objective-C header is:
This property is used by NSTextFinder to assign a find bar to a
container. The container may freely modify the view's width, but
should not modify its height. This property is managed by
NSTextFinder. You should not set this property.
Because Swift requires all instance variables to be initialized, how do I handle this situation? It appears Swift requires me to go against what Apple has wrote in the header: you should not set this property as it will be set/managed by the NSTextFinder itself.
If I don't override the NSView initializers I get:
Class 'ExampleContainerView' has no initializers
As expected since findBarView does not have an initial value.
The relevant parts of my Swift code are:
class ExampleContainerView: NSView, NSTextFinderBarContainer {
var findBarView : NSView
...
}
If I override the designated initializer to initialize findBarView as follows (ignoring Apple's comment in the header):
required init?(coder: NSCoder) {
findBarView = NSView(frame: NSRect())
super.init(coder: coder)
}
The app crashes after the NSTextFinder is sent the setFindBarContainer: message
-[NSView _setTextFinder:]: unrecognized selector sent to instance 0x6000001278a0
The object at 0x6000001278a0 is the NSView instance set in the overridden initializer above.
This appears fixed as of Xcode 7.0 beta 6. NSTextFinderBarContainer now declares findBarView as an optional NSView:
public var findBarView: NSView? { get set }
In addition, contentView() also changed to return an optional NSView:
optional public func contentView() -> NSView?
Making the property optional means there is no longer the contradiction of having the API comments say not to set findBarView, while having Swift require that all non-optional properties are initialized in in your initializers.

How to store a non-standard persistent attribute in Core Data (ex. NSRect)?

I'm struggling with my first Core Data app and not having the smoothest ride :o(
I have a drawing app with a baseclass called DrawingObject which subclasses NSManagedObject and has two properties:
#NSManaged var frameAsValue: NSValue
var frame: NSRect
DrawingObject has a subclass DrawingRectangle. All have corresponding entities with fully qualified classnames set. The frameAsValue attribute is marked as transformable and frame is marked as Undefined transient. The problem is that I get an unrecognised selector error for the frameAsValue property when creating a DrawingRectangle.
I've seen suggestions to transform NSRect to a string to save it to Core Data but this seems error prone (localization) and hackish (if thats a proper word ;o). Here is the code for DrawingObject:
class DrawingObject: NSManagedObject {
#NSManaged var frameAsValue: NSValue
var frame: NSRect = NSZeroRect {
didSet {
frameAsValue = NSValue(rect: frame)
}
}
override func awakeFromInsert() {
frame = NSMakeRect(0, 0, 0, 0)
}
override func awakeFromFetch() {
frame = frameAsValue.rectValue
}
}
I'm now assuming that you have to declare all of the inherited properties in the class hierarchy in each entity. I don't have time to test this now, but will be back soon.
You have to set parent entity of DrawingRectangle to DrawingObject to be able to inherit the properties from the parent entity (just like in the class-hierarchy). You also have to set parent--child entity relationships if you intend to save different subclasses of a parent-entity/parent-class into the same to-many relationship.
For examble if you want to save different subclasses of DrawingObjects in a #NSManaged var objects: NSSet in a Drawing for example, you have to set the parent relationships on the entities to correspond to your NSManagedObject class-hierarchy. So in this case you would set the parent of the DrawingRectangle entity to DrawingObject.
Otherwise NSRect is saved as in the code shown in the question by setting the frame-property of the DrawingObject-entity to transient and optional and the frameAsValue as transformable. You should not specify a valuetransformer so Core Data will use the default value transformer which works perfectly in this case.

Custom NSValueTransformer in xcode 6 with swift

Did anyone successfully implement a custom NSValueTransformer in xcode 6 beta with swift?
I have the following swift class:
import Foundation
class myTransformer: NSValueTransformer {
let amount = 100
override class func transformedValueClass() -> AnyClass!
{
return NSNumber.self
}
override func transformedValue(value: AnyObject!) -> AnyObject! {
return value.integerValue + amount
}
}
So all this transformer should do is, adding 100 to a given value in the gui.
As you can see, the transformer class appears now in the Value Transformer drop down in IB.
But if I choose this transformer the application crashes with:
2014-08-27 20:12:17.686 cdTest[44134:303]
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException',
reason: 'Cannot find value transformer with name newTransformer'
Is it right to register this transformer in the AppDelegate with
override class func initialize() {
let newTransformer = myTransformer()
}
Does anyone know how this whole stuff should work?
kind regards!
martin
From Xcode release notes:
If you set a Swift subclass of NSValueTransformer as a binding’s value
transformer, the XIB or storyboard will contain an invalid reference
to the class, and the binding will not work properly at runtime. You
can either enter a mangled class name into the Value Transformer field
or add the #objc(…) attribute to the NSValueTransformer subclass to
solve this problem. (17495784)
From Swift guide:
To make your Swift class accessible and usable back in Objective-C,
make it a descendant of an Objective-C class or mark it with the #objc
attribute. To specify a particular name for the class to use in
Objective-C, mark it with #objc(<#name#>), where <#name#> is the name
that your Objective-C code will use to reference the Swift class. For
more information on #objc, see Swift Type Compatibility.
Solution:
Declare your class as #objc(myTransformer) class myTransformer: NSValueTransformer and then you can use "myTransformer" as name...
After you initialise newTransformer you should also include the line:
NSValueTransformer.setValueTransformer(newTransformer, forName: "myTransformer")
Then in your Interface Builder you should use myTransformer instead of newTransformer under the Value Transformer dropdown.

Resources