The self of OC is equivalent to this in C ++. It is usually invisible, but it is not written. Actually, it's just what you mean. Who calls it? What about super? It is the parent class, and who calls it is the parent class.
Create a complex class.
(1) In complex. h
# Import <Foundation/Foundation. h> @ interface complex: nsobject // only declares attributes, and does not write the instance variable @ property (nonatomic) Double real; @ property (nonatomic) Double imag; // initialization function-(ID) initwithreal :( double) Areal imag :( double) Aimag; // addition function of the plural number-(complex *) add :( complex *) Asecond; @ end
(2) In complex. m
# Import "complex. H "@ implementation complex // do not forget @ synthesize real, imag; // initialization function-(ID) initwithreal :( double) Areal imag :( double) aimag {If (Self = [Super init]) {self. real = areal; self. imag = Aimag;} return self;} // addition function of the plural number. The return value of the function is a plural number. Only one parameter is required, and the other parameter is actually self itself-(complex *) add :( complex *) Asecond {// create a new plural here, instead of using + =, because + = will change the original value, not the best method: complex * result = [[complex alloc] init]; // here, self is who calls it, that is, a certain plural result. real = self. real + Asecond. real; result. imag = self. imag + Asecond. imag; return result;} @ end
(3) In Main. m
# Import <Foundation/Foundation. h> # import "complex. H "// remember to import the header file int main (INT argc, const char * argv []) {@ autoreleasepool {// instantiate and initialize the plural complex * A = [[complex alloc] initwithreal: 1 imag: 3]; complex * B = [[complex alloc] initwithreal: 4 imag: 2]; // Add is a method, so use [A add] to call it and pass a B parameter complex * c = [A Add: B]; nslog (@ "% G + % Gi", C. real, C. IMAG);} return 0 ;}
Returned results:
5+5i
Because of the arc function in the new version of xcode, programmers only write alloc, but do not need to write release and auturelease. Because it is automatically processed, the code is more concise. Of course, this arc function can be disabled during exercises.
[OC learning-10] Write an example of adding multiple numbers to talk about OC self. What does it mean?