views:

1504

answers:

1

I am using the actionSheet variable passed by actionSheet:didDismissWithButtonIndex: to compare the calling actionSheet to a list of UIActionSheet variables in my class. This seems to be the way the delegate method was designed to differentiate between events.

- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex {

if (actionSheet == actionSheet1) {
 switch (buttonIndex) {
  case 0:
   // Do Something
   break;
  case 1:
   // Do Something Else
   break;
  case 2:
   // Cancel
   break;
 }
}

if (actionSheet == actionSheet2) {
 switch (buttonIndex) {
  case 0:
   // Do Something
   break;
  case 1:
   // Do Something Else
   break;
  case 2:
   // Cancel
   break;
 }
}

}

Each time a UIActionSheet is displayed, I alloc an instance of UIActionSheet to one of the class variables, set the display properties, display it, and release it.

This works smoothly, at first. The problem is that after running for a while, eventually both UIActionSheet pointers (class variables actionSheet1 & actionSheet2 in the code example above) will end up pointing to the same memory, depending on what happens at runtime, thereby causing both if statements in the delegate method to evaluate true. Not good.

Now, if I were to alloc each UIActionSheet only once per run and hold on to the memory (never call release), this should not happen. But I am trying to be conservative here. Does Apple intend for the delegate to be used in this way?

+2  A: 

When you create your UIActionSheet, give it a tag:

actionSheet.tag = 1; // or 2 or 3 or ...

Then, in your delegate method, switch based on the tag to determine the behavior of that particular sheet.

August
Forgive me, but wouldn't this completely fail to work if the UIActionSheet had been released in my code? Or does the UIActionSheet class retain the instance until after the delegate is called? I suppose that would make sense but I have no way to tell.
Carson C.
You're not understanding memory management. When it reaches the delegate method, it's an autoreleased object, but it still exists and you can do anything you need with it. The fact that the delegate method gives you the actionSheet pointer should tell you that it exists, otherwise, why include it?
August
All right, that makes sense. Given that the only Autorelease pool I see is in main(), when does that pool actually release its' objects? You can see where I'm going with this: what method will release memory in the most aggressive fashion? I assume that method would then be the "best" practice.
Carson C.
I think you need a good read of the Cocoa Memory Management Guide. It has all you need to know about how memory is handled both on the Mac and the iPhone/iPod Touch: http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html
August