Re: Memory Management Mismanaged
Re: Memory Management Mismanaged
- Subject: Re: Memory Management Mismanaged
- From: "Dennis C.De Mars" <email@hidden>
- Date: Fri, 9 May 2003 10:25:28 -0700
On Friday, May 9, 2003, at 05:12 AM, Clark S. Cox III wrote:
NSMutableString *myString = [NSMutableString stringWithUTF8String:
...];
[myString appendString: @"blah"];
or
NSMutableArray *myArray = [NSMutableArray array];
[myArray addObject: @"blah"];
This is perfectly valid, legal and well formed code, but if [NSArray
array] (and therefore [NSMutableArray array]) were declared as
returning an NSArray, then the compiler would complain when you tried
to assign the result to an NSMutableArray pointer. This is the whole
reason that the factory methods must return (id).
I think it is going too far to say that factory methods MUST return id.
(I actually don't know if you were suggesting that this should be done
universally or only for theses specific classes,, but other messages in
this thread seem to suggest it is a good general rule). When id is the
return type you sacrifice static typing, so I would do it only in
specific cases where the advantages outweigh the disadvantages.
Specifically, it is a good idea if both:
1) You definitely intend to subclass, or you are designing a class that
is likely to be sub-classed.
AND
2) You have a lot of factory methods that could be meaningfully
inherited by the subclasses, and it would be tedious and/or possibly
confusing to the user to re-implement all of them for the subclasses.
When you have those two conditions then you probably want your factory
methods to return id, but I wouldn't do it universally for all factory
methods. I'd like to point out that this philosophy appears to be
followed in the Cocoa classes. For instance, all of the container
classes have a large number of factory methods, they all have "Mutable"
subclasses, and all of those subclasses can use all of the factory
methods of their base class. So, all of those factory classes return
(id). NSNumber, on the other hand, has a large number of factory
classes but does not have a mutable subclass. All of its factory
methods return (NSNumber*). It is a subclass of NSValue, which has
several factory classes returning (NSValue*) but none of these are used
by NSNumber.
If you look through the Application Kit, NSColor factory methods return
(NSColor*), NSPasteboard factory methods return (NSPasteboard*), etc.
The technique of returning (id*) is actually used rather
parsimoniously in the Cocoa API.
- Dennis D.
_______________________________________________
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.