标签:turn 调用 扩展方法 扩展 within 个数 为什么 round eval
思路:
YGInteger.h
#import <Foundation/Foundation.h> @interface YGInteger : NSObject @property(nonatomic,assign)NSInteger integer; @end
YGInteger.m 中写一个description方法,和 扩展中,将数字转换成字符串的方法
#import "YGInteger.h" #import "YGInteger_YGChangeValue.h" @implementation YGInteger - (NSString *)description { return [NSString stringWithFormat:@"%ld",self.integer]; } - (NSString *)changeValue { return [NSString stringWithFormat:@"%@",self]; } @end
YGInteger+YGInit.h 这是Integer的Init分类
#import "YGInteger.h" #import "YGInteger.h" @interface YGInteger (YGInit) - (instancetype)initWithInteger:(NSInteger)integer; + (instancetype)integerWithInteger:(NSInteger)integer; @end
YGInteger+YGInit.m 实现一下标配方法
#import "YGInteger+YGInit.h" @implementation YGInteger (YGInit) - (instancetype)initWithInteger:(NSInteger)integer { if (self = [super init]) { self.integer = integer; } return self; } + (instancetype)integerWithInteger:(NSInteger)integer { __autoreleasing YGInteger *i = [[YGInteger alloc]initWithInteger:integer]; return i; } @end
YGInteger+YGMath.h Integer的计算分类,里面有加、减、乘、除 四个方法声明。
#import "YGInteger.h" @interface YGInteger (YGMath) - (YGInteger *)add:(YGInteger *)i; - (YGInteger *)minus:(YGInteger *)i; - (YGInteger *)multiply:(YGInteger *)i; - (YGInteger *)divide:(YGInteger *)i; @end
YGInteger+YGMath.m 利用对象调用,充分体现面向对象编程。
#import "YGInteger+YGMath.h" @implementation YGInteger (YGMath) - (YGInteger *)add:(YGInteger *)i { YGInteger *result = [[YGInteger alloc]init]; result.integer = self.integer + i.integer; return result; } - (YGInteger *)minus:(YGInteger *)i { YGInteger *result = [[YGInteger alloc]init]; result.integer = self.integer - i.integer; return result; } - (YGInteger *)multiply:(YGInteger *)i { YGInteger *result = [[YGInteger alloc]init]; result.integer = self.integer * i.integer; return result; } - (YGInteger *)divide:(YGInteger *)i { YGInteger *result =[[YGInteger alloc]init]; result.integer = self.integer / i.integer; return result; } @end
YGInteger_YGChangeValue.h 最后,扩展方法中声明一下,转换的方法。
#import "YGInteger.h" @interface YGInteger () - (NSString *)changeValue; @end
先在storyBoard中先拖一个Label,用于显示结果,写一个show方法,用于把数据展示到模拟器中。
#import "ViewController.h" #import "YGInteger+YGInit.h" #import "YGInteger+YGMath.h" @interface ViewController () @property (weak, nonatomic) IBOutlet UILabel *outputLabel; - (void)show:(YGInteger *)i; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; YGInteger *int1 = [[YGInteger alloc]initWithInteger:1]; YGInteger *int2 = [[YGInteger alloc]initWithInteger:2]; YGInteger *int3 = [int1 add:int2]; self.outputLabel.text = [NSString stringWithFormat:@"%@",int3]; // [self show:[int1 add:int2]]; } - (void)show:(YGInteger *)i { self.outputLabel.text = [NSString stringWithFormat:@"%@",i]; } @end
仅此。
标签:turn 调用 扩展方法 扩展 within 个数 为什么 round eval
原文地址:http://www.cnblogs.com/Dog-Ping/p/6091118.html