OC语言day03-13description方法

pragma mark description方法

pragma mark 概念

/**
 description: 描述
 查看方法的详情: option
只要利用 %@ 打印某个对象, 系统内部默认就会调用父类的 description方法
 */

pragma mark 代码

#import <Foundation/Foundation.h>
#pragma mark 类
#import "Person.h"
#pragma mark main函数
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 只要利用 %@ 打印某个对象, 系统内部默认就会调用父类的 description方法
    // 调用该方法, 该方法会返回一个字符串,字符串的默认格式 <类的名称 : 对象的地址>
    NSLog(@"person = %@",p);    // 调用description方法
#warning [类名 class] 返回当前类的类对象
    // class注意c是小写, 只要给类 发送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来获取成员变量
    // 因为 如果您经常 在description 方法中使用self, 可能已不小心就写出了 %@",self
    // 如果在 description方法中 利用%@输出 输出self会造成死循环
    // self == person实例对象
    return [NSString stringWithFormat:@"age = %i",self.age];
}
#warning 重写 description 类方法
// 仅仅作为了解, 开始中99%@的情况 只用的都是 - 开头的description



+ (NSString *)description
{
    return @"oo";
}

 
@end

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容