[Openmcl-devel] Allocating temporary nsstrings
plkrueger at comcast.net
Sun Mar 13 07:50:09 PDT 2011
Ralph's technique will work of course, but there is also a standard way to create temporary Objective-C objects by using class constructor functions rather than using some version of the (#/init (#/alloc ...)) idiom and #/autoreleasing the result. The fact that the caller is not responsible for objects returned by class constructors is not especially well-documented, but is defined in one place that I found (which I can't recall at the moment, but is discussed somewhere in my tutorial). Ralph's suggestion actually made use of that same capability when it called #/decimalNumberWithString: and didn't worry about releasing the result of that call.
I used a class constructor to create the lisp-to-temp-nsstring function defined in
It is analogous to the objc:make-nsstring function, but uses an NSString class method so that the result is an NSString that the caller does not own and therefore is not responsible for releasing. You can just grab that if that's all you need.
It's never been entirely clear to me exactly how these Objective C class constructors are implemented. Do they re-use memory from some pool or just return an autoreleased object? They don't always seem to go away when other autorelease pools are released, but I suppose they could use a separate autorelease pool or something in much the same way that Ralph suggested. Perhaps the only advantage of using my function over Ralph's is that it saves you the trouble of creating and releasing your own autorelease pool (which would also not be necessary if you can assure that your function is always called either from a listener or as part of some event handling on the main thread where you are assured that an autorelease pool is already provided.)
On Mar 12, 2011, at 10:38 PM, Raffael Cavallaro wrote:
> On Mar 12, 2011, at 9:52 PM, Ron Garret wrote:
>> but I don't know how to stack allocate an instance of an ObjC class, or if that's even possible
> As far as I know, all objective-c objects are heap allocated (although blocks are also technically objective-c objects and they're initially stack allocated for efficiency and only copied to the heap if necessary).
> The objective-c idiom is autorelease pools combined with autorelease. Clozure CL has ccl::with-autorelease-pool, so just allocate your temporary objects and call autorelease on them inside the scope of a with-autorelease-pool form:
> ? (ccl::with-autorelease-pool
> (let ((nsstr (#/autorelease (objc:make-nsstring "-12"))))
> (#/decimalNumberWithString: ns:ns-decimal-number nsstr))))
> warmest regards,
> Raffael Cavallaro
> raffaelcavallaro at me.com
> Openmcl-devel mailing list
> Openmcl-devel at clozure.com
More information about the Openmcl-devel