
This was one of my most-used cheat sheets when I was doing heavy Objective-C work: a grab-bag of small NSString tricks, originally assembled in 2010 from the classic Borkware “Quickies” collection. The snippets below are kept exactly as they ran back then — they still compile, and they are still the clearest illustrations of the APIs involved. The original raw HTML has been converted to proper code blocks and a few typos are fixed; a section at the end maps everything onto how you’d do these jobs in 2026.
The Quickies
General
- Join an array of strings into a single string
would produce something like
NSArray *chunks = ... get an array, say by splitting it; string = [chunks componentsJoinedByString: @" /// "];
oop /// ack /// bork /// greeble /// ponies
- Split a string into an array
NSString *string = @"oop:ack:bork:greeble:ponies"; NSArray *chunks = [string componentsSeparatedByString: @":"];
- Convert a string to an integer
Similarly, there are
NSString *string = ...; int value = [string intValue];
floatValueanddoubleValueNSString methods. In Swift these survive asInt(string),Float(string), andDouble(string)initializers.
- Iterating attributes in an attributed string
This prints out each of the attribute runs from an attributed string:- (void) iterateAttributesForString: (NSAttributedString *) string { NSDictionary *attributeDict; NSRange effectiveRange = { 0, 0 }; do { NSRange range; range = NSMakeRange (NSMaxRange(effectiveRange), [string length] - NSMaxRange(effectiveRange)); attributeDict = [string attributesAtIndex: range.location longestEffectiveRange: &effectiveRange inRange: range]; NSLog (@"Range: %@ Attributes: %@", NSStringFromRange(effectiveRange), attributeDict); } while (NSMaxRange(effectiveRange) < [string length]); } // iterateAttributesForString
- Making localizable strings
You will need a file namedLocalizable.stringsthat lives in yourEnglish.lprojdirectory (or whatever localization directory is appropriate). It has this syntax:That is, a key followed by a localized value. In your code, you can then use"BorkDown" = "BorkDown"; "Start Timer" = "Start Timer"; "Stop Timer" = "Stop Timer";
NSLocalizedString()or one of its variants:The second argument is ignored by the function. Ostensibly it is a[statusItem setTitle: NSLocalizedString(@"BorkDown", nil)];
/* comment */in the strings file so that you can match the key back to what it is supposed to actually be.
- NSLog without the extra crud
NSLogputs too much crud in front of the logging line. For a foundation tool that outputs stuff, it gets in the way. I’d still like a replacement to expand%@, which theprintf()family won’t do. Here’s some code that’ll do that:#include <stdarg.h> void LogIt (NSString *format, ...) { va_list args; va_start (args, format); NSString *string; string = [[NSString alloc] initWithFormat: format arguments: args]; va_end (args); printf ("%s\n", [string UTF8String]); [string release]; } // LogIt
- Putting an image into an attributed string
You’ll need to use a text attachment.This puts the image at the front of the string. To put the image in the middle of the string, you’ll need to create an attributed string with an attachment, and then append that to your final attributed string.- (NSAttributedString *) prettyName { NSTextAttachment *attachment; attachment = [[[NSTextAttachment alloc] init] autorelease]; NSCell *cell = [attachment attachmentCell]; NSImage *icon = [self icon]; // or wherever you are getting your image [cell setImage: icon]; NSString *name = [self name]; NSAttributedString *attrname; attrname = [[NSAttributedString alloc] initWithString: name]; NSMutableAttributedString *prettyName; prettyName = (id)[NSMutableAttributedString attributedStringWithAttachment: attachment]; // cast to quiet compiler warning [prettyName appendAttributedString: attrname]; return (prettyName); } // prettyName
- Stripping out newlines from a string
So you have an NSString and want to yank out the newlines. You can do a split and join, like in scripting languages, or you can make a mutable copy and manipulate that:(This can also be used for generic string manipulations, not just stripping out newlines.) This technique takes half the time (at least) of split/join — but probably not enough to make an impact. In a simple test, split/join took 0.124 seconds to strip 36,909 newlines in a 1.5 meg textfile, and the replaceOccurrences approach took 0.071 seconds to do the same.NSMutableString *mstring = [NSMutableString stringWithString:string]; NSRange wholeShebang = NSMakeRange(0, [mstring length]); [mstring replaceOccurrencesOfString: @"\n" withString: @"" options: 0 range: wholeShebang]; return [NSString stringWithString: mstring];
- Substring matching
NSRange range = [[string name] rangeOfString: otherString options: NSCaseInsensitiveSearch];
- Today’s date as a string
The general solution for converting a date to a string is NSDateFormatter. Sometimes you need to generate a date string in a particular format easily. For instance, if you need “December 4, 2007”, you can use:(Thanks to Mike Morton for this one. Note that[[NSDate date] descriptionWithCalendarFormat: @"%B %e, %Y" timeZone: nil locale: nil]
descriptionWithCalendarFormat:is macOS-only and long deprecated in spirit — see the modern notes below.)
- Trimming whitespace from ends of a string
produces
NSString *ook = @"\n \t\t hello there \t\n \n\n"; NSString *trimmed = [ook stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]; NSLog(@"trimmed: '%@'", trimmed);2009-12-24 18:24:42.431 trim[6799:903] trimmed: 'hello there'
Graphics
- Draw a string in bold
- (void) drawLabel: (NSString *) label atPoint: (NSPoint) point bold: (BOOL) bold { NSMutableDictionary *attributes = [NSMutableDictionary dictionary]; NSFont *currentFont = [NSFont userFontOfSize: 14.0]; if (bold) { NSFontManager *fm = [NSFontManager sharedFontManager]; NSFont *boldFont = [fm convertFont: currentFont toHaveTrait: NSBoldFontMask]; [attributes setObject: boldFont forKey: NSFontAttributeName]; } else { [attributes setObject: currentFont forKey: NSFontAttributeName]; } [label drawAtPoint: point withAttributes: attributes]; } // drawLabel
Random
- Put a string on the pasteboard
Here’s a category for easily putting a string on the pasteboard:@implementation NSString (PasteboardGoodies) - (void) sendToPasteboard { [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType] owner:nil]; [[NSPasteboard generalPasteboard] setString: self forType: NSStringPboardType]; } // sendToPasteboard @end // PasteboardGoodies
Reading this in 2026
Objective-C is no longer anyone’s default choice for new Apple work — SwiftUI has been the starting point since 2019 — but all of this code still compiles, and the underlying APIs are still there. A few things to know if you’re using these snippets today:
- Memory management: the
alloc/releaseandautoreleasecalls above are manual reference counting. Since ARC arrived in 2011 you simply drop them — ARC handles the retains. - One real bug fixed: the original
LogItused[string cString], an API that was deprecated even in 2010. The snippet above now usesUTF8String, which is what you should have been calling all along. - Date work:
descriptionWithCalendarFormat:is AppKit-era convenience. The durable pattern is still NSDateFormatter with a Unicode date-format pattern — the same one my post on getting an NSDate from an NSString covers — or its Swift successor DateFormatter. - Swift equivalents: most of the “General” list collapses to one-liners in Swift:
joined(separator:)andcomponents(separatedBy:)for split/join,trimmingCharacters(in:)for trimming,range(of:options:)for substring search, andNSPasteboard.general.setStringfor the pasteboard. - Attributed strings: the attachment technique above is still how you embed an image inline in text on AppKit; on iOS the same NSTextAttachment API exists, and SwiftUI wraps the whole idea in
Text+AttributedString.
The source: these snippets come from Borkware’s legendary Quickies page (still online), which was the Stack Overflow of the pre-Stack-Overflow Objective-C world.