Unlike C ++, object-C does not stipulate that a constructor and destructor must be implemented. Therefore, in object-C, in fact, there is no such concept as constructor and destructor. Instead, it should be the creation and initialization of objects and the release of objects. Keywords related to object release. The most basic keywords are dealloc, release, and autorelease. You can use them to release objects. The instance code is as follows:
1. Define classa as follows
:
# Import <Foundation/Foundation. h>
@ Interface classa: nsobject
{
}
-(Void) hello;
@ End
@ Implementation classa
-(Void) hello
{
Nslog (@ "Hello \ n ");
}
-(Void) dealloc
{
[Super dealloc];
Nslog (@ "classa destroyed \ n ");
}
@ End
Void func ()
{
Nslog (@ "{begin \ n ");
Classa * obj1 = [[classa alloc] init];
Classa * obj2 = obj1;
[Obj1 Hello];
[Obj1 release];
[Obj2 Hello]; // Memory leakage
[Obj2 release];
Nslog (@ "} End \ n ");
}
Int main (INT argc, char ** argv)
{
Func ();
Return 0;
}
2. Compilation Method:
$ Gcc-fconstant-string-class = nsconstantstring-C memtest_realloc.m-I/gnustep/system/library/Headers
$ Gcc-O memtest_realloc memtest_realloc.o-L/gnustep/system/library/libraries/-lobjc-lgnustep-Base
$./Memtest_realloc
3. Running result:
05:47:28. 281 memtest_realloc [5484] {begin
05:47:28. 312 memtest_realloc [5484] Hello
05:47:28. 328 memtest_realloc [5484] classa destroyed
And throw the windowApplication errors are actually caused by memory leakage..
4. More test examples:
(1). Use dealloc:
[Obj1 Hello];
[Obj1Dealloc];
[Obj2 Hello];
[Obj2 release];
Running result:
Like the aboveError.
(2) Use autorelease:
Classa * obj1 = [[classa alloc] init]
Autorelease];
Classa * obj2 = obj1;
[Obj2Retain];
[Obj1 Hello]; // output hello
// For obj1, you do not need to call (actually cannot call) Release
[Obj2 Hello]; // output hello
[Obj2 release];
Running result:
06:06:19. 750 memtest_realloc [4668] {begin
06:06:19. 781 memtest_realloc [4668] autorelease called without pool fo
R object (0xdf5480) of Class classa in thread <nsthread: 0x520788>
06:06:19. 781 memtest_realloc [4668] Hello
06:06:19. 796 memtest_realloc [4668] Hello
06:06:19. 796 memtest_realloc [4668]} End
// Succeeded
5. Description:
The essence of how objects are released is how the memory is managed. Object-C does not have a garbage collection mechanism. Therefore, you need to manage objects by yourself. The simple principle is, if it is created by you, you are responsible for destruction. If it is not created by you, do not destroy it. Use release, autorelease, retain, realloc, and so on.