033.description 自我描述的方法

来源:互联网 发布:sql自定义函数 编辑:程序博客网 时间:2024/04/28 12:21
---------------  main.m  ---------------
#import<Foundation/Foundation.h>

@interfaceFKApple : NSObject
@property(nonatomic, copy) NSString* color;
@property(nonatomic, assign) double weight;
- (
id) initWithColor: (NSString*) color weight: (double) weight;
@end

@implementationFKApple
- (
id) initWithColor: (NSString*) color weight:(double) weight
{
   
if(self= [superinit])
    {
       
self.color = color;
       
self.weight = weight;
    }
   
return self;
}

- (NSString*) description
{
   return[NSString stringWithFormat:@"<FKApple[_color=%@, _weight=%g]>"
            ,
self.color , self.weight];
}
@end

intmain()
{
    FKApple* a = [[FKApple alloc] initWithColor:@红色" weight:5.68];
    NSLog(@"%@", a);
}

一、编写本节代码的具体步骤:
1.可仿照第二章001节的代码编写步骤,可以把类的接口文件,类的实现文件写在main.m文件中。

二、本节代码涉及到的知识点:
1.当我们使用NSLog函数输出一个对象的时候,输出的就是该对象的description方法的返回值。
2.description方法是NSObject类的一个方法,也就是说,所有的OC对象都具有description方法。
3.description方法默认会返回一个内存地址,如果需要更多“自我描述”,我们还得自己去重写该方法。
0 0
原创粉丝点击