Test leaks NSMutableArray. Release object with objects

В обоих примерах все впорядке:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
- (IBAction) startTestString {
     
     if (testArr == nil) {
          testArr = [[NSMutableArray alloc] init];
     }
     
     for (int i = 0; i < 100; i++) {
          [testArr addObject:@"Test text!"];
     }
     
     [testArr removeAllObjects];   
     [testArr release];
     testArr = nil;
}

// В этом примере показывается, что если вы не сделали release, то за вас его никто не сделает
- (IBAction) startTestImage {
     
     if (testArr == nil) {
          testArr = [[NSMutableArray alloc] init];
     }
     
     for (int i = 0; i < 100; i++) {
          NSString *fileLocation = [[NSBundle mainBundle] pathForResource:@"image.jpg" ofType:nil];
          UIImage *image = [[UIImage alloc] initWithContentsOfFile:fileLocation];
          [testArr addObject:image];
          [image release];  
     }
     
     NSLog(@"%d", [testArr count]);
     
     [testArr removeAllObjects];
     [testArr release];
     testArr = nil;
}

To add an element at the end of the array, you can use addObject, as in:

NSMutableArray *array;

array = [NSMutableArray new];
[array addObject: anObject];

Assuming anObject is an NSObject (but not nil, remember, you can’t put a nil object into an NSArray). As usual, anObject is RETAINed when it is added to the array.

If you want to insert an object into an array at a certain position, you can use insertObject:atIndex::

NSMutableArray *array;

array = [NSMutableArray new];
[array addObject: @"Michele"];
[array addObject: @"Nicola"];
[array insertObject: @"Alessia" atIndex: 1];

To remove an object, you can use removeObjectAtIndex:, as in

NSMutableArray *array;

array = [NSMutableArray new];
[array addObject: @"Michele"];
[array addObject: @"Nicola"];
[array insertObject: @"Alessia" atIndex: 1];

/* Now the array contains Michele, Alessia, Nicola. */

[array removeObjectAtIndex: 0];

/* Now the array contains Alessia, Nicola. */

When an object is removed from the array, it receives a release message. This balances the retain which was sent to the object when it was first added to the array, and allows the object to be deallocated, if needed.