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); } } }
但是,这种方法不知道mySecretString
或myInt
。 我绝对不想重新计算它们,我不想将它们存储为属性,因为-(void)doStuff
很less被调用。 有没有办法将这个额外的信息添加到UIAlertView,以避免重新计算或存储mySecretString
和myInt
?
谢谢!
将对象与任意其他对象关联的最快捷方式可能是使用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
被释放时自动释放。
- 什么是__NSArrayI和__NSArrayM? 如何转换为NSArray?
- UIImagePickerController在解散时搞乱了tabbar框架
- 如何给UIbuttons提供约束
- 为什么在Swift中UITableViewCell detailTextLabel是可选的,而textLabel则不是
- 在iOS中将两个文本字段添加/连接到一个标签中
- 非UIViewanimation:animation有时不玩,UIViewanimation:工作正常
- 当我重写Modern Objective-C中的setter和getters时,错误地访问生成的ivars
- 如何testingIOS设备是否具有电话function?
- 是否有可能在背景中检测到用户的移动活动?