【问题标题】:Can a UIAlertView pass a string and an int through a delegateUIAlertView 可以通过委托传递字符串和整数吗
【发布时间】:2011-03-26 00:37:21
【问题描述】:

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

谢谢!

【问题讨论】:

    标签: iphone ios uialertview


    【解决方案1】:

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

    【讨论】:

    • 这是迄今为止最好和最干净的方法。记得添加#import 来使用它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    • 1970-01-01
    • 2015-09-20
    • 1970-01-01
    相关资源
    最近更新 更多