Create a category of NSObject Class
.h
.m
1. Refer Link
2. Refer Link
.h
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#pragma mark - NSObject
@interface NSObject (CCFoundation)
- (id)associativeObjectForKey: (NSString *)key;
- (void)setAssociativeObject: (id)object forKey: (NSString *)key;
@end
.m
#pragma mark - NSObject
@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 objectForKey: key];
}
@end
-------------------:USAGE:-----------------
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"title" message:@"alert" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK",nil];
// Associate MyObject(of type id) with a key
[alertView setAssociatedObject:MyDict forKey:@"kKeyResponse"];
alertView.tag = KTagAlert;
[alertView show];
#pragma mark- Alert View Delegate-
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex;
{
if (alertView.tag == KTagNotificationAlert) {
// Fetch the associated object(id) currently dictionary
NSMutableDictionary *associatedObjectDict = [alertView associativeObjectForKey:@"kKeyResponse"];
NSLog(@"%@", associatedObjectDict);
if (associatedObjectDict) {
//Valid
switch (buttonIndex) {
case 0:{// cancel pressed
break;
}
case 1: {// ok pressed
break;
}
default:
break;
}
}
else{
[[[UIAlertView alloc]initWithTitle:@"Error" message:@"Please try later." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
}
}
}
1. Refer Link
2. Refer Link
No comments:
Post a Comment