| Sign In/My Account | View Cart |
| Article: |
Memory Management in Objective-C | |
| Subject: | (Q) interchangeable pointers and objects | |
| Date: | 2001-07-30 20:30:20 | |
| From: | psheldon | |
|
Toward the end of the last page, Mike Beam writes "Convenience constructors also make it less cumbersome to nest messages". I noted something puzzling here that I also vaguely remember from another object oriented language, Apple's object oriented pascal course I took long ago. Note above this sentence on nesting that the variable string points to a NSString, the star prefix on string is saying the thing pointed to by the variable string is an NSString type. The method setStringValue accepts this pointer. But, when we collapse things into a nest, it accepts, not a pointer to, but rather the NSString type itself. I might windily say that "the compiler is smart enough to forgive" or "the language is not context free in interpretation", but I think there is something deeper going on that makes all object oriented languages "forgive" this way, that this is "a feature and not a bug", a feature I might better exploit if I don't simply rationalize away with these windy words, but put into some sort of new rules for my writing code, rules to not merely rationalize what I have seen but also predict and help me write code I haven't seen. Perhaps there is an introductory remark somewhere, something toward these rules, so I will more fearlessly let the compiler forgive me and not fuss with such things. |
||
Showing messages 1 through 10 of 10.
All these languages are dealing with the same question: "How do I return an object from a method that will remain valid when the method goes out of scope?"
C++ takes the most straightforward approach and copies the object. There is no behind the scenes conversion from myType to myType*. This puts the burden on the programmer of defining a copy constructor for all but the most trivial classes. It also can really bog a program down in copying.
Java attempts to solve the problem with a universal garbage collector. At least in 1.2 it didn't really work and for a serious program the programmer had to manage memory "by hand." It may be fixed now.
ObjC does return a myType* and asks the programmer to autorelease it or to make it with a convenience constructor that shifts memory management duties to the class object.