Created
April 24, 2020 16:04
-
-
Save ansonj/f5c0fab0f60620517f73182a04ce866a to your computer and use it in GitHub Desktop.
Obj-C experiment: String equality
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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