NSArrayController NSTableView Core Data Binding integers - core-data

I have an NSTableView bound to an NSArrayController, which in turn is bound to Core Data. The table displays integer values from core data nicely, but if I edit the numbers in the table I get an error:
Unacceptable type of value for attribute: property = "armorclass"; desired type = NSNumber; given type = NSTaggedPointerString; value = 10.
Any suggestions of how I can convert this pointer string back to an Int16 before the Array Controller tries to save it back to Core Data?
I wrote the following ValueTransformer but it's not working properly. I always get the error: Cannot find value transformer with name StringIntegerValueTransformer
class StringIntegerValueTransformer: ValueTransformer {
override class func transformedValueClass() -> AnyClass { //What do I transform
return String.self as! AnyClass
}
override class func allowsReverseTransformation() -> Bool { //Can I transform back?
return false
}
override func transformedValue(_ value: Any?) -> Any? {
if let val = value {
return String(describing: val)
}
return "nil"
}
override func reverseTransformedValue(_ value: Any?) -> Any? { //Revert transformation
if let val = value {
return val as? Int16
}
return nil
}
}
fff

To register the value transformer override init in AppDelegate
override init()
{
let stringIntegerValueTransformer = StringIntegerValueTransformer()
ValueTransformer.setValueTransformer(stringIntegerValueTransformer, forName:NSValueTransformerName(rawValue: "StringIntegerValueTransformer"))
super.init()
}
And consider this note from the documentation
Your NSValueTransformer subclasses are not automatically listed in the Interface Builder bindings inspector. When inspecting a binding you can enter the name that the value transformer is registered with, but the functionality will not be present in Interface Builder’s test mode. When your application is compiled and run the transformer will be used

Add a number formatter to the text field.

Related

Kotlin anonymous object inheriting from base class but keeping derived class properties

I have a problem that I am not quire sure how to figure out elegantly:
abstract class BaseContinuousSingleObjectiveFitnessFunction {
// Invoke should compute some function, like f(x) = x^2 + 3x + 5
abstract fun invoke(x: List<Double>): Double
// This is supposed to take a function that will be called on the result of invoke
// and return an object derived from this one that has its invoke overriden to call
// the new function on the result of the original one.
fun modify(f: (Double) -> Double): BaseContinuousSingleObjectiveFitnessFunction {
val originalFunction = this
return object : BaseContinuousSingleObjectiveFitnessFunction() {
override operator fun invoke(x: List<Double>): Double = f(originalFunction(x))
}
}
}
Now, this works, but modify does not preserve the properties of the derived types.
So for example lets say I add this to the project:
class XTimesA(val a: Double): BaseContinuousSingleObjectiveFitnessFunction() {
override operator fun invoke(x: List<Double>) = x.sumByDouble { a*it }
}
Then I want to call modify on it:
val f1 = XTimesA(a = 5.0)
println(f1.a) // Works
val f2 = f1.modify { it.pow(2) }
println(f2.a) // This fails because it is not recognized as deriving XTimesA
Is there a way to not copy-paste modify into every deriving class but still keep access to the properties?
If you want to be able to access the property value on all inheritance levels, you have to lift the property up to the base class:
abstract class BaseContinuousSingleObjectiveFitnessFunction<Value>(val value: Value) {
abstract fun invoke(x: List<Value>): Value
fun modify(f: (Value) -> Value): BaseContinuousSingleObjectiveFitnessFunction<Value> {
val originalFunction = this
return object : BaseContinuousSingleObjectiveFitnessFunction<Value>() {
override operator fun invoke(x: List<Value>): Value = f(originalFunction(x))
}
}
}
Value is a generic type here for the case that Double is not applicable in all cases. If all values are of type Double than the class wouldn't need this type parameter.
You can use F-bounded polymorphism for this. Something like
abstract class BaseContinuousSingleObjectiveFitnessFunction<T : BaseContinuousSingleObjectiveFitnessFunction<T>> {
// Invoke should compute some function, like f(x) = x^2 + 3x + 5
abstract operator fun invoke(x: List<Double>): Double
abstract fun construct(f: (List<Double>) -> Double): T
// This is supposed to take a function that will be called on the result of invoke
// and return an object derived from this one that has its invoke overriden to call
// the new function on the result of the original one.
fun modify(f: (Double) -> Double): T = construct { list -> f(this(x)) }
}
open class XTimesA(val a: Double): BaseContinuousSingleObjectiveFitnessFunction<XTimesA>() {
override operator fun invoke(x: List<Double>) = x.sumByDouble { a*it }
override fun construct(f: (List<Double>) -> Double) = object : XTimesA(a) {
override operator fun invoke(x: List<Double>) = f(x)
}
}
However, in this particular case I don't think it actually makes sense and your example shows why: f1.modify { it.pow(2) } represents the function x -> x.sumByDouble { 5 * it }.pow(2) which isn't x -> x.sumByDouble { a * it } for any a!

Assigning default value to T:Float type parameter

I have a class that I wanted dynamic on what type to accept, but still be of type float. I have added an example class below. Simply put, I want a class that can contain either Ints or Floats (or abstracts(Float)), but the type parameter doesn't like being assigned something that should actually fit it.
class Container<T:Float>
{
public function new(aValue:T = 0.0)
{
}
public function example():T
{
return 16.0;
}
In this example, I get two compiler errors. The fist one is the default value of the constructor new(aValue:T = 0.0. A simple fix is to set the value as dynamic, but I like my code neater than this. The second error is in the return value of example(). It won't let me return 16.0, as it is not a T instance.
My question: Is this doable and, if not, should I either use different class definitions for every type?
I think the issue here is that you don't really need the generic type "T".
Here's what I came up with given your constraints. The class "Container" is not generic, and merely contains a Float constructor. This still allows it, however, to accept any value that can be implicitly cast to Float, which includes any abstract as long as they define casting rules.
package ;
class Main
{
public static function main()
{
new Container(); // default
new Container(1); // Int
new Container(2.3); // Float
new Container(new UnifiesWithFloat(4.5)); // Float abstract
}
}
class Container
{
public function new(aValue:Float = 0.8)
{
trace('aValue is $aValue');
}
}
abstract UnifiesWithFloat(Float) from Float to Float
{
inline public function new(value:Float)
{
this = value;
}
}
The only way I could come up for this issue with a cast and with own resolving of the optional parameters.
class Test {
static function main() {
$type(new Container(1));
$type(new Container(1).example());
new Container(1).example();
$type(new Container(1.0));
$type(new Container(1.0).example());
new Container(1.0).example();
}
}
class Container<T:Float> {
public var value:T;
public function new(aValue:T) {
this.value = cast (aValue != null ? aValue : 0);
}
public function example():T {
return cast 16;
}
}
This logs:
Test.hx:3: characters 14-30 : Warning : Container<Int>
Test.hx:4: characters 14-40 : Warning : Int
Test.hx:7: characters 14-32 : Warning : Container<Float>
Test.hx:8: characters 14-42 : Warning : Float

Groovy: Is there a better way of handling #Immutable objects than copyWith method

I am looking for a flexible way of "modifying" (copying with some values changed) immutable objects in groovy. There is a copyWith method but it allows you only to replace some properties of the object. It doesn't seem to be convenient enough.
Let's say we have a set of classes representing a domain design of some system:
#Immutable(copyWith = true)
class Delivery {
String id
Person recipient
List<Item> items
}
#Immutable(copyWith = true)
class Person {
String name
Address address
}
#Immutable(copyWith = true)
class Address {
String street
String postalCode
}
Let's assume I need to change street of delivery recipient. In case of regular mutable object it is just fine to perform:
delivery.recipient.address.street = newStreet
or (perhaps useful in some cases):
delivery.with {recipient.address.street = newStreet}
When it comes to do the same with immutable objects the best way according to my knowledge would be:
def recipient = delivery.recipient
def address = recipient.address
delivery.copyWith(recipient:
recipient.copyWith(address:
address.copyWith(street: newStreet)))
It is actually needed for Spock integration test code so readability and expressiveness matters. The version above cannot be used "on the fly" so in order to avoid creating tons of helper methods, I have implemented my own copyOn (since copyWith was taken) method for that which makes it possible to write:
def deliveryWithNewStreet = delivery.copyOn { it.recipient.address.street = newStreet }
I wonder however if there is an ultimate solution for that, present in groovy or provided by some external library. Thanks
For the sake of completeness I provide my implementation of copyOn method. It goes as follows:
class CopyingDelegate {
static <T> T copyOn(T source, Closure closure) {
def copyingProxy = new CopyingProxy(source)
closure.call(copyingProxy)
return (T) copyingProxy.result
}
}
class CopyingProxy {
private Object nextToCopy
private Object result
private Closure copyingClosure
private final Closure simplyCopy = { instance, property, value -> instance.copyWith(createMap(property, value)) }
private final def createMap = { property, value -> def map = [:]; map.put(property, value); map }
CopyingProxy(Object nextToCopy) {
this.nextToCopy = nextToCopy
copyingClosure = simplyCopy
}
def propertyMissing(String propertyName) {
def partialCopy = copyingClosure.curry(nextToCopy, propertyName)
copyingClosure = { object, property, value ->
partialCopy(object.copyWith(createMap(property, value)))
}
nextToCopy = nextToCopy.getProperties()[propertyName]
return this
}
void setProperty(String property, Object value) {
result = copyingClosure.call(nextToCopy, property, value)
reset()
}
private void reset() {
nextToCopy = result
copyingClosure = simplyCopy
}
}
It is then just a matter of adding the delegated method in Delivery class:
Delivery copyOn(Closure closure) {
CopyingDelegate.copyOn(this, closure)
}
High level explanation:
First of all it is required to notice that the code of: delivery.recipient.address.street = newStreet is interpreted as:
Accessing recipient property of delivery object
Accessing address of what was the result of the above
Assigning property street with the value of newStreet
Of course the class CopyingProxy does not have any of those properties, so propertyMissing method will be involved.
So as you can see it is a chain of propertyMissing method invocations terminated by running setProperty.
Base case
In order to implement the desired functionality we maintain two fields: nextToCopy (which is delivery at the beginning) and copyingClosure (which is initialised as a simple copy using copyWith method provided by #Immutable(copyWith = true) transformation).
At this point if we had a simple code like delivery.copyOn { it.id = '123' } then it would be evaluated as delivery.copyWith [id:'123'] according to simplyCopy and setProperty implementations.
Recursive step
Let's now see how would it work with one more level of copying: delivery.copyOn { it.recipient.name = 'newName' }.
First of all we will set initial values of nextToCopy and copyingClosure while creating CopyingProxy object same way as in the previous example.
Let's now analyse what would happen during first propertyMissing(String propertyName) call. So we would capture current nextToCopy (delivery object), copyingClosure (simple copying based on copyWith) and propertyName (recipient) in a curried function - partialCopy.
Then this copying will be incorporated in a closure
{ object, property, value -> partialCopy(object.copyWith(createMap(property, value))) }
which becomes our new copyingClosure. In the next step this copyingClojure is invoked in the way described in Base Case part.
Conclusion
We have then executed: delivery.recipient.copyWith [name:'newName']. And then the partialCopy applied to the result of that giving us delivery.copyWith[recipient:delivery.recipient.copyWith(name:'newName')]
So it's basically a tree of copyWith method invocations.
On top of that you can see some fiddling with result field and reset function. It was required to support more than one assignments in one closure:
delivery.copyOn {
it.recipient.address.street = newStreet
it.id = 'newId'
}

Using Swift protocols with generics

I have a simple example that seems like it should work:
import CoreData
#objc protocol CoreDataModel {
#optional class func entityName() -> String
}
class AbstractModel: NSManagedObject, CoreDataModel {
class func create<T : CoreDataModel>(context:NSManagedObjectContext) -> T {
var name = T.entityName?()
var object = NSEntityDescription.insertNewObjectForEntityForName(name, inManagedObjectContext: context) as T
return object
}
}
So we have a class called AbstractModel which conforms to the protocol CoreDataModel, and CoreDataModel defines an optional class method called entityName.
However, this line:
var name = T.entityName?()
causes the error:
Expected member name or constructor call after type name
Any idea what I'm doing wrong?
Edit
Removing the word #optional from the declaration and changing the function a bit allows the code to compile, but now I get a runtime error saying that the
'Swift dynamic cast failed'
#objc protocol CoreDataModel {
class func entityName() -> String
}
class AbstractModel: NSManagedObject, CoreDataModel {
class func entityName() -> String {
return "AbstractModel"
}
class func create<T : CoreDataModel>(aClass:T.Type, context:NSManagedObjectContext) -> T {
var name = aClass.entityName()
var object = NSEntityDescription.insertNewObjectForEntityForName(name, inManagedObjectContext: context) as T
return object
}
}
I cannot explain why your code causes a runtime exception. But it works if you change
the function prototype
class func create<T : CoreDataModel>(aClass:T.Type, context:NSManagedObjectContext) -> T
to
class func create<T : NSManagedObject where T: CoreDataModel>(aClass:T.Type, context:NSManagedObjectContext) -> T
Assuming that your managed object subclass conforms to the protocol, for example
extension Event : CoreDataModel {
class func entityName() -> String {
return "Event"
}
}
then this works and creates a new object:
let newManagedObject = AbstractModel.create(Event.self, context: context)
Alternatively, you could use the approach from the answer to
"Swift: return Array of type self" and
define an extension to the NSManagedObjectContext class:
extension NSManagedObjectContext {
func create<T : NSManagedObject where T : CoreDataModel >(entity: T.Type) -> T {
var classname = entity.entityName()
var object = NSEntityDescription.insertNewObjectForEntityForName(classname, inManagedObjectContext: self) as T
return object
}
}
Then a new object would be created as
let newManagedObject = context.create(Event.self)
From "The Swift Programming Language"
Because T is a placeholder, Swift does not look for an actual type called T.
As T is not a real type, it is maybe not useful to cast to T.

Swift class introspection & generics

I am trying to dynamically create a class instance based type using generics, however I am encountering difficulty with class introspection.
Here are the questions:
Is there a Swift-equivalent to Obj-C's self.class?
Is there a way to instantiate a class using the AnyClass result from NSClassFromString?
Is there a way to get AnyClass or otherwise type information strictly from a generic parameter T? (Similar to C#'s typeof(T) syntax)
Well, for one, the Swift equivalent of [NSString class] is .self (see Metatype docs, though they're pretty thin).
In fact, NSString.class doesn't even work! You have to use NSString.self.
let s = NSString.self
var str = s()
str = "asdf"
Similarly, with a swift class I tried...
class MyClass {
}
let MyClassRef = MyClass.self
// ERROR :(
let my_obj = MyClassRef()
Hmm… the error says:
Playground execution failed: error: :16:1: error: constructing an object of class type 'X' with a metatype value requires an '#required' initializer
Y().me()
^
<REPL>:3:7: note: selected implicit initializer with type '()'
class X {
^
It took me a while to figure out what this means… turns out it wants the class to have a #required init()
class X {
func me() {
println("asdf")
}
required init () {
}
}
let Y = X.self
// prints "asdf"
Y().me()
Some of the docs refer to this as .Type, but MyClass.Type gives me an error in the playground.
Here's how to use NSClassFromString. You have to know the superclass of what you're going to end up with. Here are a superclass-subclass pair that know how to describe themselves for println:
#objc(Zilk) class Zilk : NSObject {
override var description : String {return "I am a Zilk"}
}
#objc(Zork) class Zork : Zilk {
override var description : String {return "I am a Zork"}
}
Notice the use of the special #obj syntax to dictate the Objective-C munged name of these classes; that's crucial, because otherwise we don't know the munged string that designates each class.
Now we can use NSClassFromString to make the Zork class or the Zilk class, because we know we can type it as an NSObject and not crash later:
let aClass = NSClassFromString("Zork") as NSObject.Type
let anObject = aClass()
println(anObject) // "I am a Zork"
And it's reversible; println(NSStringFromClass(anObject.dynamicType)) also works.
Modern version:
if let aClass = NSClassFromString("Zork") as? NSObject.Type {
let anObject = aClass.init()
print(anObject) // "I am a Zork"
print(NSStringFromClass(type(of:anObject))) // Zork
}
If I'm reading the documentation right, if you deal with instances and e.g. want to return a new instance of the same Type than the object you have been given and the Type can be constructed with an init() you can do:
let typeOfObject = aGivenObject.dynamicType
var freshInstance = typeOfObject()
I quickly tested it with String:
let someType = "Fooo".dynamicType
let emptyString = someType()
let threeString = someType("Three")
which worked fine.
In swift 3
object.dynamicType
is deprecated.
Instead use:
type(of:object)
Swift implementation of comparing types
protocol Decoratable{}
class A:Decoratable{}
class B:Decoratable{}
let object:AnyObject = A()
object.dynamicType is A.Type//true
object.dynamicType is B.Type//false
object.dynamicType is Decoratable.Type//true
NOTE: Notice that it also works with protocols the object may or may not extend
Finally got something to work. Its a bit lazy but even the NSClassFromString() route did not work for me...
import Foundation
var classMap = Dictionary<String, AnyObject>()
func mapClass(name: String, constructor: AnyObject) -> ()
{
classMap[name] = constructor;
}
class Factory
{
class func create(className: String) -> AnyObject?
{
var something : AnyObject?
var template : FactoryObject? = classMap[className] as? FactoryObject
if (template)
{
let somethingElse : FactoryObject = template!.dynamicType()
return somethingElse
}
return nil
}
}
import ObjectiveC
class FactoryObject : NSObject
{
#required init() {}
//...
}
class Foo : FactoryObject
{
class override func initialize()
{
mapClass("LocalData", LocalData())
}
init () { super.init() }
}
var makeFoo : AnyObject? = Factory.create("Foo")
and bingo, "makeFoo" contains a Foo instance.
The downside is your classes must derrive from FactoryObject and they MUST have the Obj-C +initialize method so your class gets automagically inserted in the class map by global function "mapClass".
Here is another example showing class hierarchy implementation, similar to accepted answer, updated for the first release of Swift.
class NamedItem : NSObject {
func display() {
println("display")
}
required override init() {
super.init()
println("base")
}
}
class File : NamedItem {
required init() {
super.init()
println("folder")
}
}
class Folder : NamedItem {
required init() {
super.init()
println("file")
}
}
let y = Folder.self
y().display()
let z = File.self
z().display()
Prints this result:
base
file
display
base
folder
display

Resources