If I create a view, and add it as a subview and also add it to an array, do I have to release it twice?
UIView* cat = [[UIView alloc] initWithFrame:someFrame];
[self.view addSubview:cat];
[self.animals addObject:cat];
[cat release];
[cat release];
It just seems weird to me to have 2 release statements, and I haven’t seen people doing that. But doesn’t the retain count increase by 2 in this case?
You should only have one
release— to balance thealloc. NeitheraddSubView:noraddObject:give the caller ownership over the object, so the caller does not need to balance them with arelease. Reading the memory management guide should clear all this up for you.It might help to remember “NARC” — if you call a method on an object that includes the word “new”, “alloc”, “retain” or “copy”, you need to release it. As you can see in your code above, only
allocfits the bill. Since you only NARCed it once, you only need to release it once.