pragma mark description方法
pragma mark 概念
/**
description: 描述
查看方法的詳情: option
只要利用 %@ 打印某個對象, 系統(tǒng)內部默認就會調用父類的 description方法
*/
pragma mark 代碼
#import <Foundation/Foundation.h>
#pragma mark 類
#import "Person.h"
#pragma mark main函數(shù)
int main(int argc, const char * argv[])
{
Person *p = [Person new];
[p setAge:24];
[p setName:@"lyh"];
[p setWeight:80.5];
NSLog(@"age = %i, name = %@,height = %d",[p age],[p name], [p weight]);
// %@ 使用來打印對象的, 其實%@的本質是用于打印字符串
#warning 只要利用 %@ 打印某個對象, 系統(tǒng)內部默認就會調用父類的 description方法
// 調用該方法, 該方法會返回一個字符串,字符串的默認格式 <類的名稱 : 對象的地址>
NSLog(@"person = %@",p); // 調用description方法
#warning [類名 class] 返回當前類的類對象
// class注意c是小寫, 只要給類 發(fā)送class消息, 就會返回當前類的類對象
NSLog(@"當前對象 對應的 類 = %@",[Person class]);
NSLog(@"當前對象的地址 = %p",p);
return 0;
}
IPhone.h //蘋果手機 類 (子類)
#import <Foundation/Foundation.h>
@interface Person : NSObject
{
int _age;
double _height;
double _weight;
NSString *_name;
NSString *_tel;
NSString *_email;
}
// set方法
- (void)setAge:(int)age;
- (void)setHeight:(int)height;
- (void)setWeight:(int)weight;
- (void)setName:(NSString *)name;
- (void)seTtel:(NSString *)tel;
- (void)setEmail:(NSString *)email;
// getter方法
- (int)age;
- (int)height;
- (int)weight;
- (NSString *)name;
- (NSString *)tel;
- (NSString *)eamil;
@end
IPhone.m
#import "Person.h"
@implementation Person
#warning setter方法
- (void)setAge:(int)age
{
_age = age;
}
- (void)setHeight:(int)height
{
_height = height;
}
- (void)setWeight:(int)weight
{
_weight = weight;
}
- (void)setName:(NSString *)name
{
_name = name;
}
- (void)seTtel:(NSString *)tel
{
_tel = tel;
}
- (void)setEmail:(NSString *)email
{
_email = email;
}
#warning getter方法
- (int)age;
{
return _age;
}
- (int)height
{
return _height;
}
- (int)weight
{
return _weight;
}
- (NSString *)name
{
return _name;
}
- (NSString *)tel
{
return @"13";
}
- (NSString *)eamil
{
return @"email";
}
#warning 重寫 description 對象方法
// 可以重寫description方法, 返回我們需要打印的內容
// 只要利用%@打印對象, 就會調用description
// 如果打印利用的是對象調用 就會調用- 開頭的description方法
- (NSString *)description
{
/*
訪問 屬性有三種方法
p->_age;
[p age];
p.age //
self 寫在對象方法中 就 代表當時該方法的星象
*/
// NSString *str = [NSString stringWithFormat:@"age = %i, name = %@,height = %f",_age,_name,_height];
// return str;
NSLog(@"----");
#warning 建議description方法中 盡量不要使用 self來獲取成員變量
// 因為 如果您經(jīng)常 在description 方法中使用self, 可能已不小心就寫出了 %@",self
// 如果在 description方法中 利用%@輸出 輸出self會造成死循環(huán)
// self == person實例對象
return [NSString stringWithFormat:@"age = %i",self.age];
}
#warning 重寫 description 類方法
// 僅僅作為了解, 開始中99%@的情況 只用的都是 - 開頭的description
+ (NSString *)description
{
return @"oo";
}
@end
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者