UIAlertView可以传递一个string和一个int通过委托

我有一个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很less被调用。 有没有办法将这个额外的信息添加到UIAlertView,以避免重新计算或存储mySecretStringmyInt

谢谢!

将对象与任意其他对象关联的最快捷方式可能是使用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被释放时自动释放。