@fiy-fish
2015-05-19T09:44:13.000000Z
字数 2032
阅读 1366
未分类
// main.m// 类方法//// Created by Aaron on 15/5/19.// Copyright (c) 2015年 Aaron. All rights reserved.//#import <Foundation/Foundation.h>#import "Person.h"#import "Tool.h"int main(int argc, const char * argv[]){@autoreleasepool {//由类来调用的方法 类方法 +Person *p = [[Person alloc] init];//类是一个类类型的对象//ClassPerson *p1 = [[Person alloc] init];Person *p2 = [[Person alloc] init];//1.创建对象//2.作为工具[Person test1];Tool *tool = [[Tool alloc] init];[tool setNum1:9 andNum2:10 andC:'/'];NSLog(@"%d",[tool getResult]);NSLog(@"++++: %d",[Tool resultForNum1:9 andNum2:10 andC:'+']);}return 0;}
// Person.h// 类方法//// Created by Aaron on 15/5/19.// Copyright (c) 2015年 Aaron. All rights reserved.//#import <Foundation/Foundation.h>@interface Person : NSObject{int _age;}//+表示类方法//由类来调用的+(void)test1;@end
// Tool.h// 类方法//// Created by Aaron on 15/5/19.// Copyright (c) 2015年 Aaron. All rights reserved.//#import <Foundation/Foundation.h>@interface Tool : NSObject{int _num1;int _num2;char _c;}-(void)setNum1:(int)num1 andNum2:(int)num2 andC:(char)c;-(int)getResult;+(int)resultForNum1:(int)num1 andNum2:(int)num2 andC:(char)c;@end
// Tool.m// 类方法//// Created by Aaron on 15/5/19.// Copyright (c) 2015年 Aaron. All rights reserved.//#import "Tool.h"@implementation Tool-(void)setNum1:(int)num1 andNum2:(int)num2 andC:(char)c{_num1 = num1;_num2 = num2;_c = c;}-(int)getResult{int temp = 0;switch(_c){case '+':temp = _num1+_num2;break;case '-':temp = _num1-_num2;break;case '*':temp = _num1*_num2;break;case '/':temp = _num1/_num2;break;}//在实例方法里面://可以直接使用类名来访问类方法return temp;}+(int)resultForNum1:(int)num1 andNum2:(int)num2 andC:(char)c{int temp = 0;switch(c){case '+':temp = num1+num2;break;case '-':temp = num1-num2;break;case '*':temp = num1*num2;break;case '/':temp = num1/num2;break;}//在类方法里面://不能直接使用实例变量//也不能使用self访问实例变量,因为self现在是类对象,不是实例//也不能直接用self调用实例方法//如果想要在类方法里面访问实例变量//需要提供实例对象Tool *tool = [[Tool alloc] init];NSLog(@"%d",tool->_num1);return temp;}@end
// Person.m// 类方法//// Created by Aaron on 15/5/19.// Copyright (c) 2015年 Aaron. All rights reserved.//#import "Person.h"@implementation Person+(void)load{NSLog(@"加载类");}+(void)initialize{NSLog(@"创建类对象");}+(void)test1{NSLog(@".....");}@end
