Crash in Sketch script when calling .map() on boxed NSMutableArray

Hi! I’m on Sketch 2025.2.1 (205181) and have experienced a “hard” crash while developing a plugin / script.

Calling .map() in JavaScript / CocoaScript on a “boxed” (Objective-C) internal array, returned from one of the MOClassDescription introspection methods, causes Sketch to crash and die :

moc = MOClassDescription.descriptionForClassWithName(“MSTextLayer”)
items = moc.properties()
names = items.map((i) => i.name())

The items object seems to be a MOBoxedObject containing a __NSArrayM (which in turn seems to be an internal subclass of NSMutableArray).

We can avoid the crash by changing the middle line, to first “unbox” the internal array by explicitly converting it to a JavaScript array :

items = Array.from(moc.properties())

Hey there,

This is “by design” I’m afraid as you’re trying to call a JavaScript Array method (map) on an Objective-C/Swift class that just doesn’t support this method.

(well, this is not entirely true: NSArray does in fact have a map method (in Sketch environment anyway), but it doesn’t expect a JavaScript function as an argument, which is what ultimately leads to a crash. But that’s a minor implementation detail; you shouldn’t generally expect JS Array methods to work on NSArray)

By the way, there’s another useful helper function for transforming a native NSArray object into a proper JS Array:

const { toArray } = require('util');

const nativeItems = // a native NSArray instance
const items = toArray(nativeItems);
items.map(...) // etc
1 Like

Thanks! Guess I was just not expecting a plugin/script to be “allowed” to crash the whole Sketch application… (I’d have thought there would be an exception, which Sketch would catch and handle “gracefully”.)

And that’d be a fair assumption honestly! The idea behind CocoaScript (with MO classes and sketchObject, etc) is that it’s extremely powerful – meaning you can do literally anything – but at the same time it’s very fragile just like this.

In an ideal world you won’t need to even know about all this unsafe/native APIs, because the Sketch JS API would cover all of your needs. And I guess we’re getting there however slowly!

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.