In IOS programming, memory operations are inseparable. When I first came into contact with IOS programming, this is always caused by such memory problems.ProgramCrash.
In fact, the release of memory in IOS programming is relatively simple. You only need to release or autorelease your own retain, new, alloc, copy, and mutablecopy objects. One principle is: If you allocate storage, you are responsible for release.
In addition, you should note that many methods will automatically retain the added objects, such:
Nsstring * test = [[nsstring alloc] initwithformat: @ "% d", 111];
Nslog (@ "% d", [test retaincount]); // The retain of test is 1 at this time
Nsmutablearray * array = [[nsmutablearray alloc] initwithobjects: Test, nil];
Nslog (@ "% d", [test retaincount]); // at this time, the retain of test is 2. Because the test object is added to the array, test is retain.
[Array addobject: Test];
Nslog (@ "% d", [test retaincount]); // at this time, the retain of test is 3. Because the test object is added to the array, the test will be retain.
[Array release];
Nslog (@ "% d", [test retaincount]); // at this time, the retain of test is 1, and the array is released. It Automatically releases its internal objects, so the retain count of test is changed back to 1.
So after calling a method like addobject: test, if you are not using the test object, release it without worrying about "if I release test, so will the test in array be lost?" If you don't release it, it will lead to memory leakage.
Retaincount is similar to the reference count in Java. When retaincount is 0, the dealloc method of the object is called to release the object.