Мне нужно знать, должно ли сохранить
объектов всегда 0
, если я хочу иметь хорошее управление памятью в моем коде . Я получил следующий код из книги. и есть инструкция NSLog
, называемая после выпуска = 2
, так что должен ли я выпустить его еще 2 раза, чтобы удерживаемый счет
был равен 0?
#import
#import
#import
#import
#import
int main (int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSNumber *myInt = [NSNumber numberWithInteger: 100];
NSNumber *myInt2;
NSMutableArray *myArr = [NSMutableArray array];
NSLog (@”myInt retain count = %lx”,
(unsigned long) [myInt retainCount]);
[myArr addObject: myInt];
NSLog (@”after adding to array = %lx”,
(unsigned long) [myInt retainCount]);
myInt2 = myInt;
NSLog (@”after asssignment to myInt2 = %lx”,
(unsigned long) [myInt retainCount]);
[myInt retain];
NSLog (@”myInt after retain = %lx”,
(unsigned long) [myInt retainCount]);
NSLog (@”myInt2 after retain = %lx”,
(unsigned long) [myInt2 retainCount]);
[myInt release];
NSLog (@”after release = %lx”,
(unsigned long) [myInt retainCount]);
[myArr removeObjectAtIndex: 0];
NSLog (@”after removal from array = %lx”,
(unsigned long) [myInt retainCount]);
[pool drain];
return 0;
}
Программный вывод
myInt keep count = 1
после добавления в array = 2
после присвоения myInt2 = 2
myInt после сохранения = 3
myInt2 после сохранения = 3
после выпуска = 2
после удаления из массива = 1
ОБНОВЛЕНИЕ
Следующий код было взято из документа по управлению памятью Apple . Они сохранили объект NSNumber, и он никогда не выпускался, это нормально?
- (void)setCount:(NSNumber *)newCount {
[newCount retain];
[_count release];
// Make the new assignment.
_count = newCount;
}