Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
237 changes: 237 additions & 0 deletions content/guide/extending-classes-and-conforming-to-protocols-ios.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,237 @@
---
title: iOS Subclassing and conforming to protocols
---
<!-- TODO: add Preview -->

## Extending iOS classes

The following example shows how to extend the `UIViewController`:

```js
const MyViewController = UIViewController.extend({
// Override an existing method from the base class.
// We will obtain the method signature from the protocol.
viewDidLoad: function () {
// Call super using the prototype:
UIViewController.prototype.viewDidLoad.apply(this, arguments);
// or the super property:
this.super.viewDidLoad();

// Add UI to the view here...
},
shouldAutorotate: function () { return false; },

// You can override existing properties
get modalInPopover() { return this.super.modalInPopover; },
set modalInPopover(x) { this.super.modalInPopover = x; },

// Additional JavaScript instance methods or properties that are not accessible from Objective-C code.
myMethod: function() { },

get myProperty() { return true; },
set myProperty(x) { },
}, {
name: "MyViewController"
});
```

The NativeScript runtime adds the `.extend` API, as an option, which is available on any platform native class which takes an object containing platform implementations (`classMembers`) for that class and an optional second argument object defining a `nativeSignature` explained below.

You can also use the `@NativeClass()` decorator with standard class `extends` which may feel a bit more natural.

When creating custom platform native classes which extend others, always make sure their name is unique to avoid class name collisions with others on the system.

```ts
@NativeClass()
class JSObject extends NSObject implements NSCoding {
public encodeWithCoder(aCoder) { /* ... */ }

public initWithCoder(aDecoder) { /* ... */ }

public "selectorWithX:andY:"(x, y) { /* ... */ }

// An array of protocols to be implemented by the native class
public static ObjCProtocols = [ NSCoding ];

// A selector will be exposed so it can be called from native.
public static ObjCExposedMethods = {
"selectorWithX:andY:": { returns: interop.types.void, params: [ interop.types.id, interop.types.id ] }
};
}
```

:::warning Note

There should be no TypeScript constructor, because it will not be executed. Instead override one of the `init` methods.
:::

#### Exposed Method Example

As shown above, extending native classes in NativeScript take the following form:

`const <DerivedClass> = <BaseClass>.extend(classMembers, nativeSignature);`

The `classMembers` object can contain three types of methods:

- base class overrides,
- native visible methods, and
- pure JavaScript methods

The pure JavaScript methods are not accessible to native libraries. If you want the method to be visible and callable from the native libraries, pass the `nativeSignature` parameter the needed additional metadata about the method signature to `extend` with needed additional metadata about the method signature.


The `nativeSignature` argument is optional and has the following properties:

- `name` - optional, string with the derived class name
- `protocols` - optional, array with the implemented protocols
- `exposedMethods` - optional, dictionary with method `names` and `native method signature` objects

The `native method signature` object has two properties:

- `returns` - required, `type` object
- `params` - required, an array of `type` objects

The type object in general is one of the `runtime types`:

- A constructor function, that identifies the Objective-C class
- A primitive types in the `interop.types` object
- In rare cases can be a reference type, struct type etc. described with the interop API


The following example is how you can expose a pure JavaScript method to Objective-C APIs:

```js
const MyViewController = UIViewController.extend({
viewDidLoad: function () {
// ...
const aboutButton = UIButton.buttonWithType(UIButtonType.UIButtonTypeRoundedRect);
// Pass this target and the aboutTap selector for touch up callback.
aboutButton.addTargetActionForControlEvents(this, "aboutTap", UIControlEvents.UIControlEventTouchUpInside);
// ...
},
// The aboutTap is a JavaScript method that will be accessible from Objective-C.
aboutTap: function(sender) {
const alertWindow = new UIAlertView();
alertWindow.title = "About";
alertWindow.addButtonWithTitle("OK");
alertWindow.show();
},
}, {
name: "MyViewController",
exposedMethods: {
// Declare the signature of the aboutTap. We can not infer it, since it is not inherited from base class or protocol.
aboutTap: { returns: interop.types.void, params: [ UIControl ] }
}
});
```

### Overriding Initializers

Initializers should always return a reference to the object itself, and if it cannot be initialized, it should return `null`. This is why we need to check if `self` exists before trying to use it.

```js
const MyObject = NSObject.extend({
init: function() {
const self = this.super.init();
if (self) {
// The base class initialized successfully
console.log("Initialized");
}
return self;
}
});

```

## Conforming to Objective-C/Swift protocols

The following example conforms to the `UIApplicationDelegate` protocol:

```js
const MyAppDelegate = UIResponder.extend({
// Implement a method from UIApplicationDelegate.
// We will obtain the method signature from the protocol.
applicationDidFinishLaunchingWithOptions: function (application, launchOptions) {
this._window = new UIWindow(UIScreen.mainScreen.bounds);
this._window.rootViewController = MyViewController.alloc().init();
this._window.makeKeyAndVisible();
return true;
}
}, {
// The name for the registered Objective-C class.
name: "MyAppDelegate",
// Declare that the native Objective-C class will implement the UIApplicationDelegate Objective-C protocol.
protocols: [UIApplicationDelegate]
});
```

Let's look how to declare a delegate in Typescript by setting one for the [Tesseract-OCR-iOS](https://github.com/gali8/Tesseract-OCR-iOS/wiki/Using-Tesseract-OCR-iOS/6510b29bbf18655f29a26f484b00a24cc66ed88b) API

```ts
interface G8TesseractDelegate extends NSObjectProtocol {
preprocessedImageForTesseractSourceImage?(tesseract: G8Tesseract, sourceImage: UIImage): UIImage;
progressImageRecognitionForTesseract?(tesseract: G8Tesseract): void;
shouldCancelImageRecognitionForTesseract?(tesseract: G8Tesseract): boolean;
}
```

Implementing the delegate:

```ts
// native delegates often always extend NSObject
// when in doubt, extend NSObject
@NativeClass()
class G8TesseractDelegateImpl extends NSObject
implements G8TesseractDelegate {

static ObjCProtocols = [G8TesseractDelegate] // define our native protocols

static new(): G8TesseractDelegateImpl {
return <G8TesseractDelegateImpl>super.new() // calls new() on the NSObject
}

preprocessedImageForTesseractSourceImage(tesseract: G8Tesseract, sourceImage: UIImage): UIImage {
console.info('preprocessedImageForTesseractSourceImage')
return sourceImage
}

progressImageRecognitionForTesseract(tesseract: G8Tesseract) {
console.info('progressImageRecognitionForTesseract')
}

shouldCancelImageRecognitionForTesseract(tesseract: G8Tesseract): boolean {
console.info('shouldCancelImageRecognitionForTesseract')
return false
}

}
```

Using the class conforming to the `G8TesseractDelegate`:

```ts
let delegate: G8TesseractDelegateImpl;

function image2text(image: UIImage): string {
let tess: G8Tesseract = G8Tesseract.new()

// The `tess.delegate` property is weak and won't be retained by the Objective-C runtime so you should manually keep the delegate JS object alive as long the tessaract instance is alive
delegate = G8TesseractDelegateImpl.new()
tess.delegate = delegate

tess.image = image
let results: boolean = tess.recognize()
if (results == true) {
return tess.recognizedText
} else {
return 'ERROR'
}
}

```

## Limitations

- You should not extend an already extended class
- You can't override static methods or properties
- You can't expose static methods or properties
32 changes: 19 additions & 13 deletions content/sidebar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,13 +224,15 @@ export default [
text: 'Adding Native Code',
link: '/guide/adding-native-code',
},
{
text: 'Data Binding',
link: '/guide/data-binding',
},
{
text: 'Extending Native Classes',
link: '/guide/subclassing',
link: '/guide/subclassing/',
items: [
{
text: 'iOS',
link: '/guide/extending-classes-and-conforming-to-protocols-ios',
}
]
},
{
text: 'Multithreading',
Expand Down Expand Up @@ -263,24 +265,28 @@ export default [
],
},
{
text: 'Property System',
link: '/guide/property-system',
text: 'Animations',
link: '/guide/animations',
},
{
text: 'Error Handling',
link: '/guide/error-handling',
text: 'Gestures',
link: '/guide/gestures',
},
{
text: 'Shared Element Transitions',
link: '/guide/shared-element-transitions',
},
{
text: 'Animations',
link: '/guide/animations',
text: 'Data Binding',
link: '/guide/data-binding',
},
{
text: 'Gestures',
link: '/guide/gestures',
text: 'Property System',
link: '/guide/property-system',
},
{
text: 'Error Handling',
link: '/guide/error-handling',
},
],
},
Expand Down