UIAlertView可以通过委托传递字符串和int

Pen*_*One 2 iphone uialertview ios

我有一个UIAlertView(实际上有几个),-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex如果用户没有按下取消,我正在使用该方法触发一个动作.这是我的代码:

- (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];        
    }
Run Code Online (Sandbox Code Playgroud)

然后我想做的是以下内容:

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

但是,这种方法不知道mySecretStringmyInt.我绝对不想重新计算它们,我不想将它们存储为属性,因为-(void)doStuff很少(如果有的话)调用它们.有没有一种方法来此额外的信息添加到UIAlertView中,以避免重新计算或存储mySecretStringmyInt

谢谢!

Ano*_*mie 13

将对象与任意其他对象相关联的最快方法可能就是使用objc_setAssociatedObject.要正确使用它,您需要任意void *使用它作为键; 通常的做法是static char fooKey在.m文件中声明全局并&fooKey用作键.

objc_setAssociatedObject(alertView, &secretStringKey, mySecretString, OBJC_ASSOCIATION_RETAIN);
objc_setAssociatedObject(alertView, &intKey, [NSNumber numberWithInt:myInt], OBJC_ASSOCIATION_RETAIN);
Run Code Online (Sandbox Code Playgroud)

然后用于objc_getAssociatedObject稍后检索对象.

NSString *mySecretString = objc_getAssociatedObject(alertView, &secretStringKey);
int myInt = [objc_getAssociatedObject(alertView, &intKey) intValue];
Run Code Online (Sandbox Code Playgroud)

使用OBJC_ASSOCIATION_RETAIN,值将在附加到保留时保留alertView,然后在释放时自动alertView释放.