While working on project code left to me by a previous dev, I have encountered the following construct
-(NSString *)StringCheckWithString:(NSString *)string{
NSString *string2 = [NSString stringWithFormat:@"%@", string];
if([string2 length] == 0){
return @"none";
}
else {
return string2;
}
}
Can anyone explain why you would do this, it seems significantly overengineered to me and I don't understand why it has been done this way (for clarity, I don't understand why the string is formatted like this, I understand the length check)
The argument that is passed in could be any subclass of string, including NSMutableString. This code creates an immutable copy of it. This means that you can store the returned string without having to worry about someone else modifying it.
A better way of doing this would be:
NSString *string2 = [string copy];
According to the NSCopying Protocol reference:
The copy returned is immutable if the consideration “immutable vs. mutable” applies to the receiving object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With