/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~主函数~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
#import <Foundation/Foundation.h>
#import "AutoCode.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
// 1.用字典保存Person类的信息
NSDictionary *personClass = [NSDictionarydictionaryWithObjectsAndKeys:
// @"Person", @"className",
@"NSString *", @"name",
@"NSString *", @"sex",
@"NSInteger", @"age", nil];
AutoCode *auto1 = [[AutoCode alloc]init];
NSLog(@"%@", [auto1 createInitStringWith:personClass]);
}
return 0;
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Person.h~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property(nonatomic, retain)NSString *name;
@property(nonatomic, retain)NSString *sex;
@property(nonatomic, assign)NSInteger age;
- (id)initWithName:(NSString *)name sex:(NSString *)sex age:(NSInteger)age;
@end
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Person.m~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
#import "Person.h"
@implementation Person
- (id)initWithName:(NSString *)name sex:(NSString *)sex age:(NSInteger)age
{
self = [super init];
if (self) {
self.name = name;
self.sex = sex;
self.age = age;
}
return self;
}
@end
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~AutoCode.h~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
#import <Foundation/Foundation.h>
@interface AutoCode : NSObject
/// 根据字典信息,生成初始化方法源代码
-(NSString *) createInitStringWith:(NSDictionary *)classInfoDic;
@end
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~AutoCode.m~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
#import "AutoCode.h"
@implementation AutoCode
/// 根据字典信息,生成初始化方法源代码
- (NSString *)createInitStringWith:(NSDictionary *)classInfoDic
{
NSMutableString *codeing = [NSMutableStringstringWithFormat:@"- (id)initWith"];
NSArray *keys = [classInfoDic allKeys];
NSArray *values = [classInfoDic allValues];
for (int i = 0; i < [keys count]; i++) {
NSString *key = keys[i];
if (i == 0) {
[codeing appendString:[key capitalizedString]];
} else {
[codeing appendString:key];
}
[codeing appendFormat:@":(%@)%@",values[i],key];
if (i == [keys count] - 1) {
[codeing appendString:@"\n{"];
} else {
[codeing appendString:@" "];
}
}
[codeing appendString:@" self = [super init];\n"];
[codeing appendString:@" if (self) {\n"];
for (int i = 0; i < [keys count]; i++) {
[codeing appendFormat:@" self.%@ = %@;\n", keys[i], keys[i]];
}
[codeing appendString:@" }\n return self;\n}"];
return codeing;
}
@end