Basic NSString comparison

I just submitted my dissertation last week, so I should be posting a little more frequently now, despite the fact that finals are looming… Further to my post “Wrestling with OO”, I’ve actually started working on a different program, which is currently looking like this:

GFF Viewer

Yes, it’s ugly at the moment, but I only really started it on Monday, so it’s very much a work in progress. For brevity, I won’t say what it actually does, but the only real functionality at the moment is reading in a GFF file and parsing it for the names of all the DNA motifs, which are then displayed in an NSTableView.

In order to achieve this, there are a series of string comparisons that go on. Specifically, I have a nested loop that compares the DNA motif name from the current line of the GFF file (courtesy of the “outer loop”) with an NSMutableArray of unique DNA motif names, such that I end up with an array containing each DNA motif name exactly once. Simple enough. However, being a relative newcomer to “real” programming, it took me a little while to figure out that comparing NSStrings like this:
NSString *aString = @"Hello";
NSString *bString = @"Hello";
if (aString == bString)
NSLog(@"Strings are equal");
else
NSLog(@"Strings are different");

doesn’t give the “desired” result; this code would print “Strings are different”. As explained in this O’reilly macdevcenter article, this code is actually comparing “the values of [the NSString objects’] memory addresses.” Since they’re different objects, occupying different memory space, the comparison returns false. The desired code, to find if the strings themselves are different uses NSString’s isEqualToString: method, as follows:
if (aString isEqualToString:bString)
NSLog(@"Strings are equal");
else
NSLog(@"Strings are different");

Assuming aString and bString are the same as above, this code would print “Strings are equal” as expected. Simple as that. There are also way more sophisticated string comparison methods, including searching for substrings like suffixes and prefixes (using hasSuffix: and hasPrefix: respectively), performing case insensitive searches using NSCaseInsensitiveSearch as an option to the rangeOfString:options: method etc. All this is summarised, as per usual, in an extensive Apple document “String Programming Guide for Cocoa”, which can be found here.