Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C why format string as string

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)

like image 232
James Avatar asked Jul 23 '13 15:07

James


1 Answers

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.

like image 174
robbie_c Avatar answered Oct 05 '22 13:10

robbie_c