我有一个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);
}
}
}
但是,此方法不了解mySecretString
或myInt
。我绝对不想重新计算它们,我不想将它们存储为属性,因为-(void)doStuff
很少被调用。有没有办法将这些额外信息添加到UIAlertView中,以避免重新计算或存储mySecretString
和myInt
?
谢谢!
答案 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
解除分配时自动释放。