Calling Objective-C Methods from Scala
You can call Objective-C class and instance methods using the normal Scala method call syntax, if there is a binding defined for that class, e.g.:
Objective-C
Scala
[[NSNumber alloc] initWithInt:42]; NSNumber.alloc().initWithInt(42)SNCocoa provides bindings for the Foundation and AppKit frameworks, located in the packages cocoa.foundation
and cocoa.appkit, respectively.
Objective-C Functions
Bindings to global Objective-C functions are provided as functions in an object named after the framework to which they belong.
NSLog() for example is provided by cocoa.foundation.Foundation
import cocoa.foundation._
Foundation.NSLog(ns"Hello world!")
Strings and Numbers
Literals
Similar to Objective-C, SNCocoa provides short-forms to create strings and numbers from Scala literals:
Objective-C
Scala
#import <Cocoa/Cocoa.h>
NSString *thString = @"A string";
NSNumber *intNumber = @42;
NSNumber *doubleNumber = @1e42; import cocoa.foundation._
val theString = ns"A string"
val intNumber = @@(42)
val doubleNumber = @@(1e42) ns"" syntax are
not constants, but a short-hand for writing NSString.stringWithCString(c"...", NSStringEncoding.NSUTF8StringEncoding)Scala Extensions
SNCocoa provides extension methods for NSString:
import cocoa.foundation._
val nsString = ns"The String"
nsString.string // returns the NSString value as Scala string
nsString.cstring // returns the NSString value as CString
Enums
Enums defined by cocoa frameworks are represented in Scala as type aliases for NSInteger and NSUInteger,
plus a companion object that holds the enum values. For example, the values for NSStringEncoding are defined
in cocoa.foundation.NSStringEncoding:
import scalanative.native._
import cocoa.foundation._
val string = NSString.stringWithCString(c"The string", NSStringEncoding.NSUTF8StringEncoding)