Re: substring return a new string?
Re: substring return a new string?
- Subject: Re: substring return a new string?
- From: Marco Scheurer <email@hidden>
- Date: Thu, 18 Mar 2004 13:16:33 +0100
On Mar 18, 2004, at 12:00 PM, Ondra Cada wrote:
Francisco,
On Thursday, Mar 18, 2004, at 07:41 Europe/Prague, Francisco Tolmasky
wrote:
When I have a textview, and call [[textview string]
substringWithRange: someRange], if I want to save that string, do I
need to send it the copy: message, or am I ok with just retaining it
(given that the string in the textview will be edited).
presumed you want a snapshot of the moment you called
substringWithRange:, *do* use copy! It is possible that in the current
implementation it is superfluous (but harmless), but it may change in
future.
Generally, *whenever you need a snapshot of the current state, use
copy*. Use retain only in case you explicitly want to *share* the
object.
There's a mechanism of mutable/immutable objects which ensures it is
ver efficient and you don't do any unnecessary copying in fact
This is often not the case in practice. It is a common idiom, for
methods returning containers such as NSArray or NSDictionary, but also
NSString or NSData to return a mutable one which is created and filled
in the method:
- (NSArray *) someArray
{
NSMutableArray *someArray = [NSMutableArray array];
// some logic and [someArray addObject:anObject];
return someArray;
}
then what happens if you copy the returned array, is of course a real
copy instead of a retain.
(unless someone uses mutable objects for immutable data, which, of
course, is a design bug).
The above code is not a design bug, it is the only way to construct a
non trivial, constant, array. You could return [NSArray
arrayWithArray:someArray] or [[someArray copy] autorelease] instead,
but then this amounts to do a copy each time the method is executed:
very often unnecessary and inefficient.
However, it is true that if you want a snapshot, you should copy the
result. As the client of the method, only you knows if you want a
reference or a snapshot.
Marco Scheurer
Sen:te, Lausanne, Switzerland
http://www.sente.ch
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.