Skip to content

Instantly share code, notes, and snippets.

@zorn
Created April 28, 2015 22:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zorn/689dad42154d8600bdad to your computer and use it in GitHub Desktop.
Save zorn/689dad42154d8600bdad to your computer and use it in GitHub Desktop.
Demo of using a class to find the class name (minus module prefix)
import Cocoa
extension NSObject {
class func classNameNoModule() -> String {
let names = self.className().componentsSeparatedByString(".")
if let lastName = names.last {
return lastName
} else {
return self.className()
}
}
}
class MainWindowController: NSWindowController {
@IBOutlet weak var textField: NSTextField!
// MARK: NSWindowController
override var windowNibName: String? {
return MainWindowController.classNameNoModule()
}
// MARK: Actions
@IBAction func generatePassword(sender: AnyObject) {
let length = 8
let password = generateRandomString(length)
textField.stringValue = password
}
}
@Dis3buted
Copy link

Hi,
why not just use.

 self.className.componentsSeparatedByString(".").last 

in the place where you call your method/function.

@zorn
Copy link
Author

zorn commented Jun 1, 2015

My thinking at the time (even though it's not evident in the code) was trying to work out a solution for things that didn't subclass from NSObject but you are right, if you live with that assumption the one liner works fine.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment