How to export method of inner class using JSExport - ios

I have one class whose methods and properties are exported using JSExport. In normal cases, it works well. But if the property is the type of some inner class, then it can not be accessed from javascript.
Following are the classes i am using:
Person.swift
import Foundation
import JavaScriptCore
#objc
protocol PersonJavaScritMethod : JSExport {
var testProperty : OuterClassPersonal.Personal? { get set }
func sayHello(name1:String)
}
class Person : NSObject, PersonJavaScritMethod {
var name : String!
var testProperty:OuterClassPersonal.Personal?
init(name:String) {
testProperty = OuterClassPersonal.Personal()
super.init()
self.name = name
}
class func create(name : String) -> Person {
return Person(name: name)
}
func sayHello(name1:String) {
println("Hello \(name) \(name1)")
}
}
Personal.swift
import Foundation
import JavaScriptCore
#objc
protocol PersonalJavaScritMethod : JSExport {
func getNNN()
}
class OuterClassPersonal:NSObject,JSExport{
class Personal:NSObject,PersonalJavaScritMethod {
func getNNN(){
println("Hip Hip Hurray")
}
}
}
JavaScript.swift
import Foundation
import JavaScriptCore
class Javascript {
let context = JSContext()
func evaluateScript() {
context.exceptionHandler = { context, exception in
println("❌ Error in Javascript: \(exception) ");
}
var p1:Person = Person(name: "Luitel")
context.globalObject.setObject(p1, forKeyedSubscript: "Person1")
context.evaluateScript("Person1.sayHello('sdf') \n ")
var result = context.evaluateScript("Person1.testProperty.getNNN() \n")
println("\(result.toString())")
}
}
When i run the evaluateScript() method, i get the output as the following in console,
Hello Luitel sdf ❌ Error in Javascript: TypeError: undefined is not a
function (evaluating 'Person1.testProperty.getNNN()')
undefined
i want to access the method getNNN() of Personal Class. Here, if getNNN() is the method of OuterClassPersonal class and OuterClassPersonal implements PersonalJavaScriptMethod, it works properly.
The Question is, How can i access method of internal class "Personal" from Javascript?

Seems there is no way exporting inner class functions to javascript. I moved the inner class (Personal) out and created independent class and it worked.

Related

XCode 8 CoreData auto generated Base classes

I use Xcode 8 CoreData with auto generated Base classes.
When I try
let fetchRequest: NSFetchRequest<Event> = Event.fetchRequest()
fetchRequest variable correctly gets type of NSFetchRequest<Event>
When I try
let fetchRequest = Event.fetchRequest()
Xcode tells that fetchRequest has undefined type, as I understand Swift must determine type automatically by making assignment
Here is the auto generated class extension generated by Xcode
extension Event {
#nonobjc public class func fetchRequest() -> NSFetchRequest<Event> {
return NSFetchRequest<Event>(entityName: "Event");
}
#NSManaged public var ffff: String?
#NSManaged public var timestamp: NSDate?
}
As an example this code works correctly (logic is the same)
struct MyStruct<T> {
let myVar: T
}
class MyClass {
}
extension MyClass {
class func test() -> MyStruct<Int> {
return MyStruct<Int>(myVar: 5)
}
}
let b = MyClass.test()
let b has a correct type of MyStruct<Int>
CoreDate automatically generated
#objc(Event)
public class Event: NSManagedObject {
}
extension Event {
#nonobjc public class func fetchRequest() -> NSFetchRequest<Event> {
return NSFetchRequest<Event>(entityName: "Event");
}
#NSManaged public var timestamp: NSDate?
}
NSManagedObject protocol is in Objective-C and it has class method
+ (NSFetchRequest*)fetchRequest
When i try to use let fetchRequest = Event.fetchRequest() it thinks that i call Objective-C + (NSFetchRequest*)fetchRequest and it has no generics
Why doesn't it use an overridden #nonobjc public class func fetchRequest() -> NSFetchRequest<Event> from an Event class extension?

Referencing the class in it self in Class method

I would like to access the class methods inside the class it self. I know you could use self keyword in a class instance like so:
class InstanceClass {
var testProperty = "testing"
func testMathod() {
print(self.testProperty)
}
}
// initiate like so
let newInstance = InstanceClass()
newInstance.testMathod() // result testing
What's the keyword for accessing class in static property in below example:
class BaseClass {
static let testProperty = "test"
class func printProperty () {
// here I want to access testProperty
}
}
I aware that I could do BaseClass.testProperty in above example but I want to keep it abstract.
I have Swift 2.11 running.
My bad.. self keyword works with Class Methods also.
Example:
class BaseClass {
class var testProperty: String {
return "Original Word"
}
static func printTestPropery() {
print(self.testProperty)
}
}
class ChildClass: BaseClass {
override class var testProperty: String {
return "Modified Word"
}
}
ChildClass.printTestPropery() // prints "Modified Word"
I find Swift to be a little inconsistent for this but here is how you access static class properties from various scopes:
class BaseClass
{
static let testProperty = "test2"
// access class property from class function
class func printProperty()
{
print( testProperty )
}
// access class property from instance function
func printClassProperty()
{
print(BaseClass.testProperty)
print(self.dynamicType.testProperty)
}
}
protocol PrintMe:class
{
static var testProperty:String { get }
}
extension BaseClass:PrintMe {}
extension PrintMe
{
// access from a class protocol can use Self for the class
func printFromProtocol()
{
print(Self.testProperty)
}
}

Swift: inherited objects

I am getting a strange message when I use a derived class for a function with the base class as argument:
class Vehicle: Object, Mappable, Hashable, Equatable {
...
}
class Car: Vehicle {
...
}
class TransportFactory: NSObject{
func doSomethingWithVehicles(vehicles:[Vehicle]){
...
}
}
class CarFactory: TransportFactory{
let myCars = [Car]()
doSomethingWithVehicles(myCars)
}
This results in: "Cannot convert value of type '[Car]' to expected argument type '[Vehicle]'"
Object is a class (Realm), Mappable a protocol (AlamofireMapper), Hashable and Equatable a protocol from Foundation
You're declaring myCars without a type and assigning it an Array containing your Car class, so type inference is literally giving you an Array with your class object inside. Try:
let myCars = [Car]()
self.doSomethingWithVehicles(myCars)
This is why I prefer the Array<Car> syntax rather than the [Car]. I feel the code is clearer/safer, as let myCars = Array<Car> would have just not compiled.
You need to wrap doSomethingWithVehicles in a function, you can't just have it hanging out in the class scope:
class Vehicle: NSObject {
// ...
}
class Car: Vehicle {
// ...
}
class TransportFactory: NSObject {
func doSomethingWithVehicles(vehicles:[Vehicle]){
// ...
}
}
class CarFactory: TransportFactory {
let myCars = [Car]()
func someFunc() {
self.doSomethingWithVehicles(myCars)
}
}
myCars can be at the class scope because it is a class variable.
import Foundation
class Vehicle: NSObject{
}
class Car: Vehicle {
}
class TransportFactory: NSObject{
func doSomethingWithVehicles(vehicles:[Vehicle]){
print("Number of vehicles:", vehicles.count)
}
}
class CarFactory: TransportFactory {
let myCars = [Car]()
}
let carFactory = CarFactory()
carFactory.doSomethingWithVehicles(carFactory.myCars)
/* print out
Number of vehicles: 0
*/

Override default initializer of superclass in different swift files

I wrote class Vehicle in Vehicle.swift and inherited it in another class Bicycle in Bicycle.swift. But Xcode 6.1 reported an compile error: initializer does not override a designated initializer from its superclass.
Vehicle.swift:
import Foundation
public class Vehicle {
var numberOfWheels: Int?
var description: String {
return "\(numberOfWheels) wheel(s)"
}
}
Bicycle.swift:
import Foundation
public class Bicycle: Vehicle {
override init() {
super.init()
numberOfWheels = 2
}
}
Those codes are from Apple iOS Developer Library. Link: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html#//apple_ref/doc/uid/TP40014097-CH18-XID_324
When in the same .swift file, they can pass the compile. Only do not work in different files. Is this a bug of swift?
It seems, Default Initializer is invisible from other files, as if it's declared as private init() {}.
I've not found any official documents about this behavior, though. I think it's a bug.
Anyway, explicit init() declaration solves the problem.
public class Vehicle {
init() {} // <- HERE
var numberOfWheels: Int?
var description: String {
return "\(numberOfWheels) wheel(s)"
}
}
OR as #rdelmar says in comment, explicit initial value of numberOfWheels also works:
public class Vehicle {
var numberOfWheels: Int? = nil
var description: String {
return "\(numberOfWheels) wheel(s)"
}
}
Bicycle is not a public class. Code from Apple's Library:
class Bicycle: Vehicle {
override init() {
super.init()
numberOfWheels = 2
}
}

Custom class clusters in Swift

This is a relatively common design pattern:
https://stackoverflow.com/a/17015041/743957
It allows you to return a subclass from your init calls.
I'm trying to figure out the best method of achieving the same thing using Swift.
I do know that it is very likely that there is a better method of achieving the same thing with Swift. However, my class is going to be initialized by an existing Obj-C library which I don't have control over. So it does need to work this way and be callable from Obj-C.
Any pointers would be very much appreciated.
I don't believe that this pattern can be directly supported in Swift, because initialisers do not return a value as they do in Objective C - so you do not get an opportunity to return an alternate object instance.
You can use a type method as an object factory - a fairly contrived example is -
class Vehicle
{
var wheels: Int? {
get {
return nil
}
}
class func vehicleFactory(wheels:Int) -> Vehicle
{
var retVal:Vehicle
if (wheels == 4) {
retVal=Car()
}
else if (wheels == 18) {
retVal=Truck()
}
else {
retVal=Vehicle()
}
return retVal
}
}
class Car:Vehicle
{
override var wheels: Int {
get {
return 4
}
}
}
class Truck:Vehicle
{
override var wheels: Int {
get {
return 18
}
}
}
main.swift
let c=Vehicle.vehicleFactory(4) // c is a Car
println(c.wheels) // outputs 4
let t=Vehicle.vehicleFactory(18) // t is a truck
println(t.wheels) // outputs 18
The "swifty" way of creating class clusters would actually be to expose a protocol instead of a base class.
Apparently the compiler forbids static functions on protocols or protocol extensions.
Until e.g. https://github.com/apple/swift-evolution/pull/247 (factory initializers) is accepted and implemented, the only way I could find to do this is the following:
import Foundation
protocol Building {
func numberOfFloors() -> Int
}
func createBuilding(numberOfFloors numFloors: Int) -> Building? {
switch numFloors {
case 1...4:
return SmallBuilding(numberOfFloors: numFloors)
case 5...20:
return BigBuilding(numberOfFloors: numFloors)
case 21...200:
return SkyScraper(numberOfFloors: numFloors)
default:
return nil
}
}
private class BaseBuilding: Building {
let numFloors: Int
init(numberOfFloors:Int) {
self.numFloors = numberOfFloors
}
func numberOfFloors() -> Int {
return self.numFloors
}
}
private class SmallBuilding: BaseBuilding {
}
private class BigBuilding: BaseBuilding {
}
private class SkyScraper: BaseBuilding {
}
.
// this sadly does not work as static functions are not allowed on protocols.
//let skyscraper = Building.create(numberOfFloors: 200)
//let bigBuilding = Building.create(numberOfFloors: 15)
//let smallBuilding = Building.create(numberOfFloors: 2)
// Workaround:
let skyscraper = createBuilding(numberOfFloors: 200)
let bigBuilding = createBuilding(numberOfFloors: 15)
let smallBuilding = createBuilding(numberOfFloors: 2)
Since init() doesn't return values like -init does in Objective C, using a factory method seems like the easiest option.
One trick is to mark your initializers as private, like this:
class Person : CustomStringConvertible {
static func person(age: UInt) -> Person {
if age < 18 {
return ChildPerson(age)
}
else {
return AdultPerson(age)
}
}
let age: UInt
var description: String { return "" }
private init(_ age: UInt) {
self.age = age
}
}
extension Person {
class ChildPerson : Person {
let toyCount: UInt
private override init(_ age: UInt) {
self.toyCount = 5
super.init(age)
}
override var description: String {
return "\(self.dynamicType): I'm \(age). I have \(toyCount) toys!"
}
}
class AdultPerson : Person {
let beerCount: UInt
private override init(_ age: UInt) {
self.beerCount = 99
super.init(age)
}
override var description: String {
return "\(self.dynamicType): I'm \(age). I have \(beerCount) beers!"
}
}
}
This results in the following behavior:
Person.person(10) // "ChildPerson: I'm 10. I have 5 toys!"
Person.person(35) // "AdultPerson: I'm 35. I have 99 beers!"
Person(35) // 'Person' cannot be constructed because it has no accessible initializers
Person.ChildPerson(35) // 'Person.ChildPerson' cannot be constructed because it has no accessible initializers
It's not quite as nice as Objective C, since private means all the subclasses need to be implemented in the same source file, and there's that the minor syntax difference Person.person(x) (or Person.create(x) or whatever) instead of simply Person(x), but practically speaking, it works the same.
To be able to instantiate literally as Person(x), you could turn Person into a proxy class which contains a private instance of the actual base class and forwards everything to it. Without message forwarding, this works for simple interfaces with few properties/methods but it gets unwieldy for anything more complex :P
I think actually the Cluster pattern can be implemented in Swift using runtime functions. The main point is to replace the class of your new object with a subclass when initializing. The code below works fine though I think more attention should be paid to subclass' initialization.
class MyClass
{
var name: String?
convenience init(type: Int)
{
self.init()
var subclass: AnyClass?
if type == 1
{
subclass = MySubclass1.self
}
else if type == 2
{
subclass = MySubclass2.self
}
object_setClass(self, subclass)
self.customInit()
}
func customInit()
{
// to be overridden
}
}
class MySubclass1 : MyClass
{
override func customInit()
{
self.name = "instance of MySubclass1"
}
}
class MySubclass2 : MyClass
{
override func customInit()
{
self.name = "instance of MySubclass2"
}
}
let myObject1 = MyClass(type: 1)
let myObject2 = MyClass(type: 2)
println(myObject1.name)
println(myObject2.name)
protocol SomeProtocol {
init(someData: Int)
func doSomething()
}
class SomeClass: SomeProtocol {
var instance: SomeProtocol
init(someData: Int) {
if someData == 0 {
instance = SomeOtherClass()
} else {
instance = SomethingElseClass()
}
}
func doSomething() {
instance.doSomething()
}
}
class SomeOtherClass: SomeProtocol {
func doSomething() {
print("something")
}
}
class SomethingElseClass: SomeProtocol {
func doSomething() {
print("something else")
}
}
Basically you create a protocol that your class cluster inherits from. You then wrap around an instance variable of the same type and choose which implementation to use.
For example, if you were writing an array class that switched between a LinkedList or a raw array then SomeOtherClass and SomethingElseClass might be named LinkedListImplementation or PlainArrayImplementation and you could decide which one to instantiate or switch to based on whatever is more efficient.
There is a way to achieve this. Whether it is good or bad practice is for another discussion.
I have personally used it to allow for extension of a component in plugins without exposing the rest of the code to knowledge of the extensions. This follows the aims of the Factory and AbstractFactory patterns in decoupling code from the details of instantiation and concrete implementation classes.
In the example case the switching is done on a typed constant to which you would add in extensions. This kinda contradicts the above aims a little technically - although not in terms of foreknowledge. But in your case the switch might be anything - the number of wheels for example.
I don’t remember if this approach was available in 2014 - but it is now.
import Foundation
struct InterfaceType {
let impl: Interface.Type
}
class Interface {
let someAttribute: String
convenience init(_ attribute: String, type: InterfaceType = .concrete) {
self.init(impl: type.impl, attribute: attribute)
}
// need to disambiguate here so you aren't calling the above in a loop
init(attribute: String) {
someAttribute = attribute
}
func someMethod() {}
}
protocol _Factory {}
extension Interface: _Factory {}
fileprivate extension _Factory {
// Protocol extension initializer - has the ability to assign to self, unlike class initializers.
init(impl: Interface.Type, attribute: String) {
self = impl.init(attribute: attribute) as! Self;
}
}
Then in a concrete implementation file ...
import Foundation
class Concrete: Interface {
override func someMethod() {
// concrete version of some method
}
}
extension InterfaceType {
static let concrete = InterfaceType(impl: Concrete.self)
}
For this example Concrete is the "factory" supplied default implementation.
I have used this, for example, to abstract the details of how modal dialogs were presented in an app where initially UIAlertController was being used and migrated to a custom presentation. None of the call sites needed changing.
Here is a simplified version that does not determine the implementation class at runtime. You can paste the following into a Playground to verify its operation ...
import Foundation
class Interface {
required init() {}
convenience init(_ discriminator: Int) {
let impl: Interface.Type
switch discriminator {
case 3:
impl = Concrete3.self
case 2:
impl = Concrete2.self
default:
impl = Concrete1.self
}
self.init(impl: impl)
}
func someMethod() {
print(NSStringFromClass(Self.self))
}
}
protocol _Factory {}
extension Interface: _Factory {}
fileprivate extension _Factory {
// Protocol extension initializer - has the ability to assign to self, unlike class initializers.
init(impl: Interface.Type) {
self = impl.init() as! Self;
}
}
class Concrete1: Interface {}
class Concrete2: Interface {}
class Concrete3: Interface {
override func someMethod() {
print("I do what I want")
}
}
Interface(2).someMethod()
Interface(1).someMethod()
Interface(3).someMethod()
Interface(0).someMethod()
Note that Interface must actually be a class - you can't collapse this down to a protocol avoiding the abstract class even if it had no need for member storage. This is because you cant invoke init on a protocol metatype and static member functions cannot be invoked on protocol metatypes. This is too bad as that solution would look a lot cleaner.
We can take advantage of a compiler quirk - self is allowed to be assigned in protocol extensions - https://forums.swift.org/t/assigning-to-self-in-protocol-extensions/4942.
Thus, we can have in place something like this:
/// The sole purpose of this protocol is to allow reassigning `self`
fileprivate protocol ClusterClassProtocol { }
extension ClusterClassProtocol {
init(reassigningSelfTo other: Self) {
self = other
}
}
/// This is the base class, the one that gets circulated in the public space
class ClusterClass: ClusterClassProtocol {
convenience init(_ intVal: Int) {
self.init(reassigningSelfTo: IntChild(intVal))
}
convenience init(_ stringVal: String) {
self.init(reassigningSelfTo: StringChild(stringVal))
}
}
/// Some private subclass part of the same cluster
fileprivate class IntChild: ClusterClass {
init(_ intVal: Int) { }
}
/// Another private subclass, part of the same cluster
fileprivate class StringChild: ClusterClass {
init(_ stringVal: String) { }
}
Now, let's give this a try:
print(ClusterClass(10)) // IntChild
print(ClusterClass("abc")) // StringChild
This works the same as in Objective-C, where some classes (e.g. NSString, NSArray, NSDictionary) return different subclasses based on the values given at initialization time.

Resources