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

时间:2011-03-26 00:37:21

标签: iphone ios uialertview

我有一个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];        
    }

然后我想做的是:

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

但是,此方法不了解mySecretStringmyInt。我绝对不想重新计算它们,我不想将它们存储为属性,因为-(void)doStuff很少被调用。有没有办法将这些额外信息添加到UIAlertView中,以避免重新计算或存储mySecretStringmyInt

谢谢!

1 个答案:

答案 0 :(得分:13)

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

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

然后使用objc_getAssociatedObject稍后检索对象。

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

使用OBJC_ASSOCIATION_RETAIN,这些值会在附加到alertView时保留,然后在alertView解除分配时自动释放。

相关问题