Skip to content

objc: Add function to convert NSString to Go string #438

Description

@TotallyGamerJet

Operating System

  • Windows
  • macOS
  • Linux
  • FreeBSD
  • Android
  • iOS

What feature would you like to be added?

A function that converts from NSString to a Go string

// NSStringToString returns a copy of the contents of an NSString into a Go string
// If the ID is 0 then an empty string is returned.
// If the ID is not an NSString class then the function panics.
func NSStringToString(str ID) string {
	if str == 0 {
		return ""
	}
	if str.Send(selIsKindOf, nsStringClass) == 0 {
		return panic("objc: provided ID is not an NSString")
	}
	return strings.GoString(uintptr(str.Send(selUTF8String)))
}

Why is this needed?

This is a common operation that people want to do and it is easy to do incorrectly.

I originally did it wrong in this PR by using length which is UTF-16 codepoint instead of utf8 length.

It is also currently wrong here.

Activity

  1. hajimehoshi commented on Mar 12, 2026

    @hajimehoshi
    Member

    It is also currently wrong here.

    Oops, is this a bug..?

  2. hajimehoshi commented on Mar 12, 2026

    @hajimehoshi
    Member

    I agree this should be a very useful utility function

  3. added this to the v0.11.0 milestone on Mar 12, 2026
  4. TotallyGamerJet commented on Mar 12, 2026

    @TotallyGamerJet
    CollaboratorAuthor

    It is also currently wrong here.

    Oops, is this a bug..?

    Technically, yes but I don't think it'd cause any issues since I don't think the NSAppearance returns any non-ascii characters. That is only the case where the UTF-16 code point length returned from the length selector would differ from the UTF-8 code point length.

  5. hajimehoshi commented on Mar 12, 2026

    @hajimehoshi
    Member

    Sure. I'll fix this asap, but if NSStringToString is introduced, I'll use it.

  6. added a commit that references this issue on May 9, 2026
    f8849c8
  7. added a commit that references this issue on Aug 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions