Skip to content

Instantly share code, notes, and snippets.

@darknoon
Last active July 31, 2018 09:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save darknoon/af7ee904573c1a1154987eb2b0c4e8f8 to your computer and use it in GitHub Desktop.
Save darknoon/af7ee904573c1a1154987eb2b0c4e8f8 to your computer and use it in GitHub Desktop.
You can use ivars so you don't need to make so many hilarious classes
// Make a class with some handlers.
function Class(handlers){
var uniqueClassName = "fetchDelegate_" + NSUUID.UUID().UUIDString();
var cls = MOClassDescription.allocateDescriptionForClassWithName_superclass_(uniqueClassName, NSObject);
// Add each handler to the class description
for(var selectorString in handlers) {
var sel = NSSelectorFromString(selectorString);
cls.addInstanceMethodWithSelector_function_(sel, handlers[selectorString]);
}
// Add ivar to store instance-specific info
const ok = cls.addInstanceVariableWithName_typeEncoding("extraInfo", "@");
return cls.registerClass();
};
const cls = Class({
// Use this new syntax, but not arrow syntax to make sure we can still access the instance as this
"test"() {
log("extra = " + this.valueForKey("extraInfo"))
},
});
const instance = cls.new();
// Slightly inelegant, can use properties to make it a bit shorter
instance.setValue_forKey({a:123}, "extraInfo");
instance.test();
/* Output
extra = {
a = 123;
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment