Objective-Everything Release 5. Copyright ©1994-1998 by TipTop Software, Inc. All Rights Reserved.
The (SV*) type: ...
Reference counting. You never need to retain/release ObjPerl objects. The Objective-Perl system does it automatically behind the scenes! E.g.:
$o=NSObject->alloc->init; $o->release; $o->retainCount; # ==> 1 # ... undef $o; # o is released now!
Note that NSAutoreleasePools are an exception to how the ObjPerl system handles reference counting, since NSAutoreleasePools cannot be retained (i.e., their retain count is always 1) in OpenStep. NSAutoreleasePools are NOT automatically retained nor automatically released. To release a NSAutoreleasePool you must send it an explicit release message!
Normal object release/retain behavior --- objects are automatically retained/released:
$a=NSObject->alloc->init; $a->retainCount; # ==> 2 # ... $a->release; # a is not dealloced yet undef $a; # a is released and dealloced now!
The special NSAutoreleasePool retain/release behavior --- NSAutoreleasePools are NOT automatically retained/released. The following two are equivalent:
$p=NSAutoreleasePool->alloc->init; $p->retainCount(); # ==> 1 # ... # if we only do: undef $p; pool p would not be released! $p->release; # p is released now! undef $p; # be nice
Here is an example showing how to use NSAutoreleasePools:
$pool=NSAutoreleasePool->alloc->init; $o=NSObject->alloc->init; $o->retainCount; # ==> 2 # ... $o->autorelease; # ... $o->retainCount; # ==> greater than 1 since o is autoreleased! undef $o; # o is not dealloced yet!! $pool->release; # releases the pool, and this releases/deallocates the object undef $pool;
Freeing stuff (in -dealloc). If you have an instance variable which is type (char*), and you want to free it (e.g., in a -dealloc method), simply assign it value None. E.g.:
class 'XYZ', 'NSObject', 'id anObject; char *aStr; /*...*/'; extend 'XYZ', { '-(void)dealloc' => sub { my($self)=shift; $self->{'anObject'}=nil; # releases self->anObject $self->{'aStr'}=undef; # frees self->aStr self->SUPER::dealloc; }
};
Passing arguments "by reference" in Perl. In Perl, arguments to subs are passed "by-reference". E.g., consider:
sub myincr { print "sub myincr: ",$_[0]++,"\n"; }
$i=3; myincr $i; # prints: sub myincr: 3 print "i=$i\n"; # prints: i=4
Recall that when you invoke a method from Perl, the arguments get converted to low-level (ObjC) types. If the method invoked is implemented in ObjPerl, the argument values are converted back into Perl types. Hence, you cannot pass Perl variables "by-reference" into ObjPerl implemented methods:
category_begin 'NSObject'; method '+(void)myincr:(int)i', sub { print "method myincr: ",$_[2]++,"\n"; } category_end;
$i=7;
NSObject->myincr_($i); # prints: method myincr: 7 print "i=$i\n"; # prints: i=7