Artifice refers to a skill and a product that is too kit and useless.
Reprint please indicate the source Uxyheaven csdn Blog
In fact, this technique is very useful in certain circumstances, and the requirements are not high.
We had an interface 1, designed .... For the sake of flexibility, we used a dictionary.
- (void)method1:(NSDictionary *)dic{ NSString *name = dic[@"name"]; NSLog(@"%s, name: %@",__FUNCTION__, name);}
By the time we improve, we find that the code should be written like this
@protocol protocol <NSObject>- (NSString *)name;@end- (void)method2:(id <protocol>)objc{ NSString *name = objc.name; NSLog(@"%s, name: %@",__FUNCTION__, name);}
So the problem is, METHOD1 has been you do not know how many places, how to change the cost of the least?
We can disguise an object as a dictionary
//. h @interface normalentity : nsobject @property(nonatomic, copy)NSString*name;@endAs_pretenddictionary (normalentity)//. M @implementation normalentity @endDef_pretenddictionary (normalentity);//Core @protocol pretenddictionaryprotocol<nsobject>- (void) SetObject: (ID) obj Forkeyedsubscript: (ID<NSCopying>) key;-(ID) Objectforkeyedsubscript: (ID) key;@end#define As_pretenddictionary (__class) \ @interface __class (pretenddictionary) \- (void) SetObject: (ID) obj Forkeyedsubscript: (ID<NSCopying>) key; - (ID) Objectforkeyedsubscript: (ID) key;@end#define Def_pretenddictionary (__class) \ @implementation __class (pretenddictionary) \- (void) SetObject: (ID) obj Forkeyedsubscript: (ID<NSCopying>) Key {[ SelfSetvalue:obj Forkeypath: (NSString*) key]; } - (ID) Objectforkeyedsubscript: (ID) Key {return[ SelfValueforkeypath:key]; }@end
When you use it, you can do it straight when he's a dictionary.
NormalEntity *bb = [[NormalEntity alloc] init]; bb[@"name"] = @"aaa"; [self method1:(NSDictionary *)bb];
Of course, this and the real dictionary still has a difference, can only get and set, otherwise it will not be in this series.
Demo can be downloaded here
OBJECTIVE-C Kit Kat--to disguise the object as a dictionary