Skip to content

Instantly share code, notes, and snippets.

@jemgold
Forked from darknoon/classWithIvar.cocoascript.js
Last active March 21, 2017 05:04
Show Gist options
  • Save jemgold/8b9c6a76650810e264cf78fc72c5dac1 to your computer and use it in GitHub Desktop.
Save jemgold/8b9c6a76650810e264cf78fc72c5dac1 to your computer and use it in GitHub Desktop.
You can use ivars so you don't need to make so many hilarious classes
class Class {
constructor(ivars = []) {
const uniqueClassName = "fetchDelegate_" + NSUUID.UUID().UUIDString();
const cls = MOClassDescription.allocateDescriptionForClassWithName_superclass_(uniqueClassName, NSObject);
const prototype = Object.getPrototypeOf(this);
Object.getOwnPropertyNames(prototype).forEach(prop => {
console.log(prop);
const sel = NSSelectorFromString(prop);
cls.addInstanceMethodWithSelector_function_(sel, prototype[prop]);
})
ivars.forEach(ivar => {
cls.addInstanceVariableWithName_typeEncoding(ivar, "@");
})
const instance = cls.registerClass().new();
this._instance = instance;
return this;
}
get(key) {
return this._instance.valueForKey(key)
}
set(key, value) {
return this._instance.setValue_forKey(value, key)
}
}
class MySillyClass extends Class {
fooFooFoo() {
const foo = this.get('foo');
return foo + foo + foo;
}
}
const inst = new MySillyClass(['foo', 'bar', 'baz'])
inst.set('foo', 'bar');
log(inst.get('foo'))
log(inst.fooFooFoo())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment