开发者

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

开发者 https://www.devze.com 2023-02-19 16:22 出处:网络
I have a UIAlertView (several, in fact), and I\'m using the method -(void)alertView:(UIAlertView *)alertViewclickedButtonAtIndex:(NSInteger)buttonIndex to trigger an action if the user doesn\'t press

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);
        }
    }
}

How开发者_开发百科ever, 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!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号