CruorVult
CruorVult

Reputation: 823

J2ObjC: How to translate own type

I want to create class-adapter for platform specific code. For example, there are 2 classes:

Java:

class SQLiteAdapter {
    public void executeSql() {
        //use android.database.sqlite
    }
}

Objective C

@interface SQLiteAdapter : NSObject {}
- (void)executeSql;
@end

How to "teach" J2ObjC converts java code

SQLiteAdapter adapter = new SQLiteAdapter();
adapter.executeSql();

to

SQLiteAdapter* adapter =  [SQLiteAdapter alloc];
[adapter executeSql]

Upvotes: 0

Views: 115

Answers (1)

tball
tball

Reputation: 2044

You can use sqlighter, a j2objc-compatible library that lets you write your database access code once for Android and iOS. Since it wraps the SQLite libraries on the two platforms, it's easy to switch.

If you really want to implement your own cross-platform API, normally the app uses an interface or abstract class that defines the API, and separate implementations for each platform are loaded using a dependency injection framework like Dagger, or Java reflection.

Using your code as a starting point, first define a SQLiteAdapter as an abstract class, with an abstract executeSql() method:

public abstract class SQLiteAdapter {
  public abstract void executeSql();
}

Next, define an AndroidSQLiteAdapter that extends SQLiteAdapter and implements executeSql() using your Android-specific code:

class AndroidSQLiteAdapter extends SQLiteAdapter {
  public void executeSql() {
    //use android.database.sqlite
  }
}

Finally, translate SQLiteAdapter.java with j2objc, and modify your iOS class:

#import "SQLiteAdapter.h"
#import <sqlite3.h>

@interface IosSQLiteAdapter : SQLiteAdapter
@end

@implementation IosSQLiteAdapter
- (void)executeSql {
  // Implement using SQLite C API.
}
@end

Upvotes: 1

Related Questions