Peter Lapisu
Peter Lapisu

Reputation: 20975

Returning mutable where return value should be immutable

i found this code

-(NSString *) genRandStringLength: (int) len {

    NSMutableString *randomString = [NSMutableString stringWithCapacity: len];

    for (int i=0; i<len; i++) {
         [randomString appendFormat: @"%C", [letters characterAtIndex: arc4random() % [letters length]]];
    }

    return randomString;
}

is it ok to pass a mutable object, where the result is immutable?

so should we do?

return [randomString copy];

or

return randomString;

Upvotes: 0

Views: 112

Answers (2)

Ole Begemann
Ole Begemann

Reputation: 135550

Technically, it is no problem to return an NSMutableString instead of an NSString. Since the former is a subclass of the latter, an NSMutableString instance supports everything an NSString does. If you look at Cocoa, you'll notice, for example, that many alloc/init methods return an instance of a subclass of the class you wanted to create.

In your particular case, I see no problem if the method returns a mutable string because the string has been created locally in that method and is not being used in other places in the class.

Generally, you should probably avoid returning mutable objects if these objects are ivars/properties of the class that returns them. If you do such a thing, the caller of the method could find out that the returned object is mutable and then change its contents without notifying the "owning" instance of the object about the changes.

Also note that, if you want to return an immutable object, return [randomString copy]; is only correct under ARC and garbage collection. With manual memory management, it should be return [[randomString copy] autorelease]; or return [NSString stringWithString:randomString];.

Upvotes: 4

Maulik
Maulik

Reputation: 19418

You can do :-

-(NSString *) genRandStringLength: (int) len
{
  NSMutableString *randomString = [NSMutableString stringWithCapacity: len];

  for (int i=0; i<len; i++) {
     [randomString appendFormat: @"%C", [letters characterAtIndex: arc4random() % [letters length]]];
  }

  NSString *immutableString = [NSString stringWithString:randomString];

  //OR

  NSString *immutableString = (NSString *)randomString;

  return immutableString;
}

Upvotes: 0

Related Questions