創(chuàng)建一個Person類
Person.h
import<Foundation/Foundation.h>
@interface Person : NSObject
{
//屬性
NSString *_name;//名字
int _age; //年齡
float _weight; //體重
}
/*______________________________________________________________________*/
//方法聲明
//set 方法 設(shè)置器
- (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;
//調(diào)用本類的實例方法 使用 --> self 表示本類的對象
[self privateMethod];
//調(diào)用本類的類方法 使用 --> 類名
[Person classPrivateMethod];
}
/*______________________________________________________________________*/
//如果一個方法實現(xiàn)在 .m 文件中,而沒有在對應(yīng)的 .h 文件中聲明 那么這是一個私有的方法
- (void)privateMethod
{
NSLog(@"私有方法");
}
+ (void)classPrivateMethod
{
NSLog(@"私有的類方法");
}
/*________________________________________________________________________*/
//description 方法 方法覆寫
- (NSString *)description
{
//決定了 使用%@打印對象時 控制臺所展示的內(nèi)容
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
{
//類 創(chuàng)建 對象
//1.開辟內(nèi)存
Person *xiaoming = [Person alloc];
//2.初始化
xiaoming = [xiaoming init];
//建議寫法:一次完成
Person *xiaohong = [[Person alloc]init];
/*_____________________________________________________________________*/
//設(shè)置屬性
[xiaohong setName:@"小紅"];
[xiaohong setAge:18];
[xiaohong setWeight:120];
[xiaohong setName:@"小紅"];
/*_______________________________________________________________________*/
//訪問屬性
NSLog("name = %@ age = %d weight = %f",[xiaohong name],[xiaohong age],[xiaohong weight]);
/*_______________________________________________________________________*/
//類 調(diào)用 類方法
[Person showPersonMembers];
NSLog(@"xiaohong is %@"xiaohong);
}
return 0;
}