Can a UIAlertView pass a string and an int through a delegate

倾然丶 夕夏残阳落幕 提交于 2019-12-03 06:14:03

问题


I have a UIAlertView (several, in fact), and I'm using the method -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex to trigger an action if the user doesn't press cancel. Here's my code:

- (void)doStuff {   
        // complicated time consuming code here to produce:
        NSString *mySecretString = [self complicatedRoutine];
        int myInt = [self otherComplicatedRoutine];

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"HERE'S THE STUFF" 
                                                        message:myPublicString // derived from mySecretString
                                                       delegate:nil 
                                              cancelButtonTitle:@"Cancel" 
                                              otherButtonTitles:@"Go On", nil];
        [alert setTag:3];
        [alert show];
        [alert release];        
    }

and then what I would like to do would be the following:

- (void)alertView:(UIAlertView *)alertView 
clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        if ([alertView tag] == 3) {
                        NSLog(@"%d: %@",myInt,mySecretString);
        }
    }
}

However, this method doesn't know about mySecretString or myInt. I definitely don't want to recalculate them, and I don't want to store them as properties since -(void)doStuff is rarely, if ever, called. Is there a way to add this extra information to the UIAlertView to avoid recalculating or storing mySecretString and myInt?

Thanks!


回答1:


Probably the quickest way to associate an object with an arbitrary other object is to use objc_setAssociatedObject. To use it correctly, you need an arbitrary void * to use as a key; the usual way to do that is to declare a static char fooKey globally in your .m file and use &fooKey as the key.

objc_setAssociatedObject(alertView, &secretStringKey, mySecretString, OBJC_ASSOCIATION_RETAIN);
objc_setAssociatedObject(alertView, &intKey, [NSNumber numberWithInt:myInt], OBJC_ASSOCIATION_RETAIN);

Then use objc_getAssociatedObject to retrieve the objects later.

NSString *mySecretString = objc_getAssociatedObject(alertView, &secretStringKey);
int myInt = [objc_getAssociatedObject(alertView, &intKey) intValue];

Using OBJC_ASSOCIATION_RETAIN, the values will be retained while attached to the alertView and then automatically released when alertView is deallocated.



来源:https://stackoverflow.com/questions/5439560/can-a-uialertview-pass-a-string-and-an-int-through-a-delegate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!