0
votes

everyone! I'm using Xcode 6.2 now for developing objective-c, when i try to use "Instruments" to detecting memory issues, it just not work as i were see books or blogs.I use the code blow to test(main function is omitted, using default xcode&instruments settings).

for(int i=0; i<2; i++)
{
    KSTestObj *obj0 = [[KSTestObj alloc] init];
    KSTestObj *obj1 = [[KSTestObj alloc] init];
    obj0.obj = obj1;
    obj1.obj = obj0;
}
sleep(100);

and the KSTestObj class just has a NSObject propety. Here is a strange phenomenon. When I set i<1, the "Instruments" capture nothing, and when i<2(or bigger), it can detect a memory problem by Leaks! BUT the leaked objects number is 2(or 2*times-2)!Thats ODD! Anyone knows what going on? Did i made any mistakes? tks! here is the picture & log: i<2, and "Instruments" detect 2 object leaked.

2015-06-27 14:33:19.108 ObjCPro_Test[50820:603] init success! 0x7ff968700c10
2015-06-27 14:33:19.109 ObjCPro_Test[50820:603] init success! 0x7ff968700c20
2015-06-27 14:33:19.109 ObjCPro_Test[50820:603] init success! 0x7ff9687003a0
2015-06-27 14:33:19.110 ObjCPro_Test[50820:603] init success! 0x7ff9687003b0
<End of Run>

enter image description here

i<1, "Instruments" shows no leaked objects!

2015-06-27 14:30:17.737 ObjCPro_Test[50789:603] init success! 0x7f7ff1e00830
2015-06-27 14:30:17.738 ObjCPro_Test[50789:603] init success! 0x7f7ff1e004e0
<End of Run>

enter image description here

1

1 Answers

0
votes

If obj0 contains a strong reference to obj1, and obj1 also contains a strong reference to obj0, you've created a retain cycle, where neither object can be released.

This will leak memory, for each object, for each iteration through the loop. (That's exactly why it's 2 x number of iterations - 1.)

To solve this, you could set the obj property to weak, so each object can go out of existence at the conclusion of an iteration.