Code:
@import Foundation;/************************************************** * Man class **************************************************/@interfaceMan:nsobject//Potential risk: Use the property modifier copy to modify a property of a mutable type@property (copy, nonatomic) nsmutablestring *name;@end@implementationMans@end/************************************************** * Main function **************************************************/intMainintargcConst Char*argv[]) {@autoreleasepool {nsmutablestring*namemutablestring = [nsmutablestring stringwithstring:@"AAA"]; Mans*man =[[Man alloc] init]; //When a property is assigned a value by its set method, the actual type of the property value will be the immutable type, and its execution is similar to the following statement//man->_name = namemutablestring.copy;Man.name =namemutablestring; //the type of the property is no longer an immutable typeNSLog (@"[man.name IsKindOfClass:NSMutableString.class] =%@", [Man.name iskindofclass:nsmutablestring.class] ?@"YES":@"NO"); NSLog (@"[man.name IsKindOfClass:NSString.class] =%@", [Man.name iskindofclass:nsstring.class] ?@"YES":@"NO"); //The program may crash if you execute the following statement//[Man.name setstring:@ "BBB"]; } return 0;}
Output:
[Man.name iskindofclass:nsmutablestring. class] = no[man.name iskindofclass:nsstring. class] = YES
Summarize:
Use the property modifier with caution copy to modify properties of a mutable type
Variable type properties and copy