Skip to content

Instantly share code, notes, and snippets.

@ansonj
Created April 24, 2020 16:04
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 ansonj/f5c0fab0f60620517f73182a04ce866a to your computer and use it in GitHub Desktop.
Save ansonj/f5c0fab0f60620517f73182a04ce866a to your computer and use it in GitHub Desktop.
Obj-C experiment: String equality
#import <Foundation/Foundation.h>
#define SAMPLE @"one sample string value"
NSString *addressOf(id object) {
return [NSString stringWithFormat:@"%p", object];
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
{
// Using the same string literal produces the same instance
NSString *one = SAMPLE;
NSString *two = SAMPLE;
assert([one isEqualToString:two]);
assert([one isEqual:two]);
assert(one == two);
assert([addressOf(one) isEqualToString:addressOf(two)]);
}
{
// Using `copy` produces the same instance
NSString *one = SAMPLE;
NSString *two = one.copy;
assert([one isEqualToString:two]);
assert([one isEqual:two]);
assert(one == two);
assert([addressOf(one) isEqualToString:addressOf(two)]);
}
{
// Grant's example
NSString *str = @"TestStr";
// Compiler warning: Direct comparison of a string literal has undefined behavior
assert(str == @"TestStr"); // (but it still works!)
}
{
// Force creating different instances for the same contents
NSString *one = SAMPLE;
NSString *two = [@"one sample " stringByAppendingString:@"string value"];
assert([one isEqualToString:two]);
assert([one isEqual:two]);
// !
assert(one != two);
// !
assert(![addressOf(one) isEqualToString:addressOf(two)]);
// Now we can test the array behavior
NSArray *arr = @[one, two];
assert([arr containsObject:one]);
assert([arr containsObject:two]);
assert([arr containsObject:SAMPLE]);
}
NSLog(@"Survived with no failures!");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment