创建一个Person类
Person.h
import<Foundation/Foundation.h>
@interface Person : NSObject
{
//属性
NSString *_name;//名字
int _age; //年龄
float _weight; //体重
}
/*______________________________________________________________________*/
//方法声明
//set 方法 设置器
- (void)setName:(NSString *)name;
- (void)setAge:(int)age;
- (void)setWeight:(float)weight;
//get方法 访问器
- (NSString *)name;
- (int)age;
- (float)weight;
/*______________________________________________________________________*/
//类方法
+ (void)showPersonMembers;
//实例方法
- (void)setName:(NSString *)name age:(int)age weight:(float)weight;
@end
Person.m
#import"Person.h"
@implementation Person
//set
- (void)setName:(NSString *)name
{
_name = name;
}
- (void)setAge:(int)age
{
_age = age;
}
- (void)setWeight:(float)weight
{
_weight = weight;
}
/*_______________________________________________________________*/
//get
- (NSString *)name
{
return _name;
}
- (int)age
{
return _age;
}
- (float)weight
{
return _sweight;
}
/*_________________________________________________________________*/
//类方法
+ (void)showPersonMembers
{
NSLog(@"members : name age sweight");
}
//实例方法
- (void)setName:(NSString *)name age:(int)age weight:(float)weight
{
[self setName:name];
_age = age;
_weight = weght;
//调用本类的实例方法 使用 --> self 表示本类的对象
[self privateMethod];
//调用本类的类方法 使用 --> 类名
[Person classPrivateMethod];
}
/*______________________________________________________________________*/
//如果一个方法实现在 .m 文件中,而没有在对应的 .h 文件中声明 那么这是一个私有的方法
- (void)privateMethod
{
NSLog(@"私有方法");
}
+ (void)classPrivateMethod
{
NSLog(@"私有的类方法");
}
/*________________________________________________________________________*/
//description 方法 方法覆写
- (NSString *)description
{
//决定了 使用%@打印对象时 控制台所展示的内容
return [NSString stringWithFormat:@"Person:%p name:%@ age:%d weight%,1f",self,_name,_age,_weight];
}
@end
main.m
#import<Foundation/Foundation.h>
#import"Person.h"
int main(int argc,const char *argv[])
{
@autoreleasepool
{
//类 创建 对象
//1.开辟内存
Person *xiaoming = [Person alloc];
//2.初始化
xiaoming = [xiaoming init];
//建议写法:一次完成
Person *xiaohong = [[Person alloc]init];
/*_____________________________________________________________________*/
//设置属性
[xiaohong setName:@"小红"];
[xiaohong setAge:18];
[xiaohong setWeight:120];
[xiaohong setName:@"小红"];
/*_______________________________________________________________________*/
//访问属性
NSLog("name = %@ age = %d weight = %f",[xiaohong name],[xiaohong age],[xiaohong weight]);
/*_______________________________________________________________________*/
//类 调用 类方法
[Person showPersonMembers];
NSLog(@"xiaohong is %@"xiaohong);
}
return 0;
}
网友评论