How to add userInfo to a UIAlertView?

前端 未结 5 1854
终归单人心
终归单人心 2020-12-01 04:39

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

Thank you.

5条回答
  •  再見小時候
    2020-12-01 05:23

    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 
    #import 
    
    @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! :-)

提交回复
热议问题