0

I have an NSMutableArray of Person(NSManagedObject) which is a property of a UIViewController PersonsViewController (presented as modal) and is used as a datasource of a UITableView to list all persons. The array is populated from Core Data. On didSelectRowAtIndexPath I set selectedPerson which is a strong, nonatomic property in the presentingViewController.

In PersonsViewController the user can delete items from the UITableView. How do I handle the reference selectedPerson if the deleted item from the array happens to be the object selectedPerson is pointing to?

Lukas
  • 694
  • 1
  • 9
  • 24

3 Answers3

2

Since you are using a property, just set it to nil if it is selected...

[personsArray removeObject:personToDelete];
if (self.selectedPerson == personToDelete)
    self.selectedPerson = nil;

That should release it and it should get dealloc'd...

jjv360
  • 4,120
  • 3
  • 23
  • 37
  • Wow that simple! Why didn't I try that. I guess I wasn't sure the == would have worked. Thanks a million @jjv360 – Lukas Apr 19 '13 at 09:56
0

Since you are having strong reference to the selected object,removing the person object from array during deletion will not affect the selected person.

As per ARC, object will reside in memory if it have at least one strong reference. So in your case removing the person from array will cancel the strong reference the array has with the person object but you still have one strong reference using the selected person pointer.

So selected person become the elegible candidate to stay in memory and you can use it wihout fear.

RJR
  • 1,072
  • 2
  • 9
  • 21
  • Unfortunately since selectedPerson is an `NSManagedObject` the properties are no longer accessible returning a when accessing the object. – Lukas Apr 19 '13 at 09:58
0

The short answer is selectedPerson = nil;.

Under ARC that will remove the strong reference to the object so it can be removed from memory.

In your code you can test

if ( selectedPerson ) 
{
    /* do something to that selected person */
}

to see if you still have a selected person.

uulhaa
  • 121
  • 3