Last active
October 7, 2015 16:17
-
-
Save EvgenyKarkan/314f8b8e6d202a47caeb to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Case 1 | |
// A modifiable pointer to a constant NSString. | |
// | |
NSString* john = @"John"; | |
NSString* const userName1 = john; | |
//If we try like below - an error occurs because userName1 is a modifiable pointer to a constant NSString, so its value can't be modified | |
//userName1 = @"Not John"; // Invalid -> Read-only variable is not assignable | |
//But lets try to break the pointer itself. | |
// ARC cannot infer what storage type it should use. So you have to tell it | |
// This loses the const qualifier, so the compiler is warning you of that fact. | |
NSString* __strong * notJohn = &userName1; | |
*notJohn = @"Not John"; | |
NSLog(@"USER 1 name is %@", userName1); //prints Not John | |
// Case 2 | |
// A constant pointer to an modifiable NSString (its value can't be modified). | |
// | |
NSString* tom = @"Tom"; | |
const NSString* userName2 = tom; | |
tom = @"Not Tom"; | |
userName2 = tom; | |
NSLog(@"USER 2 name is %@", userName2); // prints TOM 2 | |
// Case 3 - most safe way | |
// A constant pointer to a constant NSString | |
// | |
NSString* bob = @"Bob"; | |
const NSString* const userName3 = bob; | |
bob = @"Not Bob"; | |
// If we try assigning like below - error occurs | |
//userName3 = bob; // Bingo we've got error: -> Read-only variable is not assignable |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment