Problem with NSMutableCharacterSet removeCharactersInString

This snippet makes SD crash and returns no result if run from FastScripts.
It used to work for years since now I upgraded to Monterey and SD8.
Is there a workaround?

use framework "Foundation"

set theSet to (current application's NSMutableCharacterSet's alphanumericCharacterSet()'s invertedSet())
(theSet's removeCharactersInString:"|_")

Update : I made a test. This code does not crash SD7. And the script it’s part of works well.

Hi ionah. {“|_”} is a list.

Bonjour Nigel,

It’s a typo. I’ve amended my previous post.

Under macOS 13 it crashes both SD8 and Script Editor identically – it appears to be happening in a CoreFoundation function. Please report it to Apple.

I wonder if the result is not actually mutable. Give this a try:

use framework "Foundation"

set theSet to (current application's NSMutableCharacterSet's alphanumericCharacterSet()'s invertedSet())'s mutableCopy()
(theSet's removeCharactersInString:"|_")

Shane, you’re awesome!

Bug report is done.

It’s probably crashing FastScripts, too, but since FastScripts now runs everything in a separate script runner, you’re not seeing anything happen. It’s on my list to report crashes of script runners so scenarios like this are a bit less confusing.

The root of this problem is in fact that invertedSet returns an NSCharacterSet. NSMutableCharacterSet overrides many other methods such as alphaNumericCharacterSet, so they remove return a mutable character set. I think the way to frame this to Apple would be to request that they add an override for invertedSet to NSMutableCharacterSet.

@ShaneStanley’s workaround is good.

I could have sworn I checked this, but of course I didn’t – thanks, @redsweater . The mutable near-equivalent is simply invert. So:

use framework "Foundation"

set theSet to current application's NSMutableCharacterSet's alphanumericCharacterSet()
theSet's invert()
(theSet's removeCharactersInString:"|_")

I used ˋ(current application’s NSMutableCharacterSet’s alphanumericCharacterSet()'s invertedSet()) for years and it was returning a ˋmutableCharacterSetˋ.
The confusing part was not that FS (silently) crashes but why SD7 was not.

The reporting of runner’s crash is a good news. Thanks for that.

Does invert() can be used with any set or array?

No. Inverting only makes sense for a character set because it has a defined full state.

1 Like

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