views:

24

answers:

1

I am trying desperately to change the images on an OpenFlow instance with no luck. I am kind of giving up so I am trying now to remove the instance and create a new one. But I can't avoid crashing the app.

The code to create it is:

AFOpenFlowView *of = [[AFOpenFlowView alloc] initWithFrame:CGRectMake(0, 100, 320, 380)];
 [of setCenter:CGPointMake(160, 240)];
 [of setBackgroundColor:[UIColor blackColor]]; 
 [of setDataSource:self];
 [of setViewDelegate:self];

 [self setPeopleFlow:of];      
 [self.view addSubview:peopleFlow];

 [of release];

Then, on a click of a button I do:

[peopleFlow removeFromSuperview];
[peopleFlow release];

Later on I call the same function with the first block of code to create it again and it's when the application crashes with no log error.

Any ideas on how to clean the OpenFlow object to repopulate it without having to remove/recreate? Or how create/recreate reliably?

Thanks.

A: 

When you create the peopleFlow instance, it has a retain count of 1.

Then when you add it as a subview, the super view retains it, so it's retain count is 2.

Then you release it after adding it to the superview, so it's retain count is 1 again.

Then You remove it from the superview, and the superview releases it, so it's retain count is 0 and the object gets deallocated.

Then you try and release it again, and it crashes because you're sending release to a deallocated object.

Long story short, in this case, you don't need to release it after removing it from the superview.

Also, it is good practise to assign nil to a pointer if you release it and don't care about what is pointing at any more. This is because after you release and deallocate an object, the pointer variable is still pointing to the memory that the object used to occupy. Assigning nil to the pointer prevents any bad stuff happening if you try to send a message to whatever the dangling pointer is pointing to.

Jasarien
Thanks so much.I didn't quite understand the how the retain counting worked. But I feel I got a better understanding now.brilliant answer.
jordi