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;
Technically, it is no problem to return an
NSMutableStringinstead of anNSString. Since the former is a subclass of the latter, anNSMutableStringinstance supports everything anNSStringdoes. 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 bereturn [[randomString copy] autorelease];orreturn [NSString stringWithString:randomString];.