如何将 userInfo 添加到 UIAlertView 中?

发布于 2024-10-21 23:55:44 字数 73 浏览 1 评论 0原文

我想知道如何将 userInfo 对象或任何 NSDictionary 添加到 UIAlertView 中?

谢谢。

I would like to know how to add a userInfo object, or any NSDictionary, to a UIAlertView?

Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

触ぅ动初心 2024-10-28 23:55:44

您可以尝试子类化 UIAlertView 来添加字段,或者将引用存储在委托类中。但将任何对象附加到任何其他对象的最通用方法是使用 objc_setAssociatedObject 。

为此,您必须 #import,并且需要一个任意 void * 用作键(通常的技巧是在 .m 文件中声明一个 static char fooKey; 并使用其地址)。然后你可以像这样附加对象:

objc_setAssociatedObject(alertView, &fooKey, myDictionary, OBJC_ASSOCIATION_RETAIN);

在这种情况下,myDictionary 将在alertView 的生命周期内保留,并在alertView 被释放时被释放。

要稍后检索关联对象,请使用逻辑命名的 objc_getAssociatedObject

NSDictionary *myDictionary = objc_getAssociatedObject(alertView, &fooKey);

如果没有设置关联,则返回nil。要打破关联,只需使用 objc_setAssociatedObject 为同一对象和键关联一个新值即可; nil 可用于中断关联而不关联新对象。

列出了除 OBJC_ASSOCIATION_RETAIN 之外的关联类型的其他值 此处

You could try subclassing UIAlertView to add the field, or store a reference in your delegate class instead. But the most general way to attach any object to any other object is to use objc_setAssociatedObject.

To do so, you have to #import <objc/runtime.h>, and you need an arbitrary void * that is used as a key (the usual trick is to declare a static char fooKey; in your .m file and use its address). Then you can attach the object like this:

objc_setAssociatedObject(alertView, &fooKey, myDictionary, OBJC_ASSOCIATION_RETAIN);

In this case, myDictionary will be retained for the life of the alertView and will be released when the alertView is deallocated.

To retrieve your associated object later, use the logically named objc_getAssociatedObject.

NSDictionary *myDictionary = objc_getAssociatedObject(alertView, &fooKey);

It returns nil if there was no association set. To break the association, just use objc_setAssociatedObject to associate a new value for the same object and key; nil can be used to break the association without associating a new object.

Other values for the type of association besides OBJC_ASSOCIATION_RETAIN are listed here.

游魂 2024-10-28 23:55:44

我在 NSObject 上编写了一个(经过充分测试的)类别,它使每个对象都能够轻松存储数据。

只需将代码放入标头和实现文件中,然后将其导入到您的任何项目中即可。或者放在静态库中。仅限 Mac OS X 10.6+ 和 iOS(版本?)。

#import <Foundation/Foundation.h>
#import <objc/runtime.h>

@interface NSObject (CCFoundation)

- (id)associativeObjectForKey: (NSString *)key;
- (void)setAssociativeObject: (id)object forKey: (NSString *)key;

@end

#pragma mark -

@implementation NSObject (CCFoundation)

static char associativeObjectsKey;

- (id)associativeObjectForKey: (NSString *)key {
    NSMutableDictionary *dict = objc_getAssociatedObject(self, &associativeObjectsKey);
    return [dict objectForKey: key];
}

- (void)setAssociativeObject: (id)object forKey: (NSString *)key {
    NSMutableDictionary *dict = objc_getAssociatedObject(self, &associativeObjectsKey);
    if (!dict) {
        dict = [[NSMutableDictionary alloc] init];
        objc_setAssociatedObject(self, &associativeObjectsKey, dict, OBJC_ASSOCIATION_RETAIN);
    } [dict setObject: object forKey: key];
}

@end

简而言之,只要您需要,每个对象都会变成一本易于使用的字典(感谢 NSMutableDictionary)。当对象被释放时,字典也被释放;当字典被释放时,字典的对象也被释放。令人惊奇的是苹果公司如何让这一切变得如此简单。

警告 1:上面的代码启用了 ARC。它经过充分测试并用于多种已发货的产品中。我还没有看到任何内存泄漏或性能问题。

警告 2:根据需要重命名方法,但如果您选择保留名称,请确保添加前缀。这是根对象“人”的类别。某处的某些类正在使用此方法名称,您不想干涉!我在每个项目中包含的静态库都使用方法名称 associativeCCObjectForKey:setAssociativeCCObject:forKey:

我希望这可以帮助任何想要在每个对象上拥有简单的类似 userInfo 功能的人。不客气! :-)

I wrote a (well-tested) category on NSObject that gives every object the capability to easily store data.

Just put the code in a header and implementation file and import it in any of your projects. Or put it in a static library. Mac OS X 10.6+ and iOS (version?) only.

#import <Foundation/Foundation.h>
#import <objc/runtime.h>

@interface NSObject (CCFoundation)

- (id)associativeObjectForKey: (NSString *)key;
- (void)setAssociativeObject: (id)object forKey: (NSString *)key;

@end

#pragma mark -

@implementation NSObject (CCFoundation)

static char associativeObjectsKey;

- (id)associativeObjectForKey: (NSString *)key {
    NSMutableDictionary *dict = objc_getAssociatedObject(self, &associativeObjectsKey);
    return [dict objectForKey: key];
}

- (void)setAssociativeObject: (id)object forKey: (NSString *)key {
    NSMutableDictionary *dict = objc_getAssociatedObject(self, &associativeObjectsKey);
    if (!dict) {
        dict = [[NSMutableDictionary alloc] init];
        objc_setAssociatedObject(self, &associativeObjectsKey, dict, OBJC_ASSOCIATION_RETAIN);
    } [dict setObject: object forKey: key];
}

@end

Simply put, every object becomes an easy-to-use dictionary (thanks to NSMutableDictionary) as soon as you need one. The dictionary is released when the object is and the dictionary's objects are released when the dictionary is released. It's amazing how Apple made this simple.

Warning 1: The code above is ARC enabled. It's well-tested and is used in several shipped products. I didn't see yet any memory leaks or performance issues.

Warning 2: Rename the methods as you wish, but if you choose to keep the name, make sure you add a prefix. This is a category on a root object, people. Some class somewhere is using this method name and you don't want to interfere! My static library which I include in every project uses the method names associativeCCObjectForKey: and setAssociativeCCObject:forKey:.

I hope this helps anybody wanting to have a simple userInfo-like feature on every object. You're welcome! :-)

祁梦 2024-10-28 23:55:44

如果您在 > iOS 4.0(对于块)并且您只需要一两个按钮,您可以使用我制作的此类别:

https: //github.com/rsaunders100/UIAlertView-Blocks

它绕过了添加用户信息的需要,因为您将点击处理函数直接放入警报中。例如

 #import UIAlertView+Blocks.h

 ...

 ...

 NSString* myUserInfo = @"example";

 [UIAlertView displayAlertWithTitle:@"Example Alert View With Blocks"
                            message:nil
                    leftButtonTitle:@"Ok"
                  leftButtonAction:^{
                                      NSLog(@"%@", myUserInfo);
                                    } 
                  rightButtonTitle:nil
                 rightButtonAction:nil];

If you are on > iOS 4.0 (for blocks) and you only want one or two buttons, you could use this category I made:

https://github.com/rsaunders100/UIAlertView-Blocks

It bypasses the need to add user info since you put your click handeling function straight into the alert. e.g.

 #import UIAlertView+Blocks.h

 ...

 ...

 NSString* myUserInfo = @"example";

 [UIAlertView displayAlertWithTitle:@"Example Alert View With Blocks"
                            message:nil
                    leftButtonTitle:@"Ok"
                  leftButtonAction:^{
                                      NSLog(@"%@", myUserInfo);
                                    } 
                  rightButtonTitle:nil
                 rightButtonAction:nil];
沦落红尘 2024-10-28 23:55:44

如果我给它一个文字 C 字符串(例如“key”)而不是创建静态字符,它对我有用

,它对我有用相反,考虑到 Anomie 所说的,你可以这样做:

objc_setAssociatedObject ( alert , (const void*)0x314 , notification , OBJC_ASSOCIATION_RETAIN ) ;

这适用于任何允许你使用任意 void* 的东西(观察、此函数等)并且不需要额外的静态变量技巧。另外,(const void*)0x314 始终是 0x314,无论编译器做什么。

另外,Anomie,您刚刚为我正在开发的应用程序节省了很多工作。谢谢!

It works for me if i give it a literal c string such as "key" instead of creating a static char

Instead, taking into account what Anomie says, you could instead do this:

objc_setAssociatedObject ( alert , (const void*)0x314 , notification , OBJC_ASSOCIATION_RETAIN ) ;

This works for anything which allows you to use arbitrary void* (observation, this function, etc) and requires no extra static variable tricks. Also, (const void*)0x314 is ALWAYS 0x314, no matter what the compiler does.

Also, Anomie, you just saved me a LOT of work in an app I'm working on right now. Thanks!

抚你发端 2024-10-28 23:55:44

我提出了一个更简单的解决方案,可能适合某些情况。因为调用委托时您会获得 NSAlertView 上下文,所以我使用对象的实际地址来创建一个标记 (NSString*),然后使用该标记将自定义值存储在全局或特定于对象的 NSDictionary 中。下面是一个示例:

+(NSString*)GetTag:(id)ObjectIn
{
    return [NSString stringWithFormat:@"Tag-%i",(int)ObjectIn];
}

在委托中:

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString* MyID = [CommandManager GetTag:alertView];
    [CurrentActiveAlerts removeObjectForKey:MyID];
}

调用:

    UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:title_text
                                                          message:@""
                                                     delegate:self
                                            cancelButtonTitle:nil
                                        otherButtonTitles:button_text ,nil];

    CurrentActiveAlerts[[CommandManager GetTag:myAlert]] = CommandToRun;  
    [myAlert show];
    [myAlert release];

键最终看起来像“Tag-226811776”。希望这有帮助。

I've come up with a simpler solution that may fit in some circumstances. Because you get the NSAlertView context when the delegate gets called, I use the actual address of the object to make a tag (NSString*) which I then use to store custom values in a global or object specific NSDictionary. Here is an example:

+(NSString*)GetTag:(id)ObjectIn
{
    return [NSString stringWithFormat:@"Tag-%i",(int)ObjectIn];
}

In the Delegate:

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString* MyID = [CommandManager GetTag:alertView];
    [CurrentActiveAlerts removeObjectForKey:MyID];
}

Calling:

    UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:title_text
                                                          message:@""
                                                     delegate:self
                                            cancelButtonTitle:nil
                                        otherButtonTitles:button_text ,nil];

    CurrentActiveAlerts[[CommandManager GetTag:myAlert]] = CommandToRun;  
    [myAlert show];
    [myAlert release];

The keys will end up looking like "Tag-226811776". Hope this helps.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文