//
// Teacher.h
// description
//
// Created by LiuWei on 15/4/15.
// Copyright (c) 2015年 LiuWei. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Teacher : NSObject
@end
//
// Teacher.m
// description
//
// Created by LiuWei on 15/4/15.
// Copyright (c) 2015年 LiuWei. All rights reserved.
//
#import "Teacher.h"
@implementation Teacher
@end
//
// Student.h
// description
//
// Created by LiuWei on 15/4/15.
// Copyright (c) 2015年 LiuWei. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Student : NSObject
@property NSString *name;
@property int age;
- (NSString*)description;
+ (NSString*)description;
@end
//
// Student.m
// description
//
// Created by LiuWei on 15/4/15.
// Copyright (c) 2015年 LiuWei. All rights reserved.
//
#import "Student.h"
@implementation Student
- (NSString *)description
{
return [NSString stringWithFormat:@"name:%@, age:%i", _name, _age];
}
+ (NSString *)description
{
return @"Class name is Student";
}
@end
//
// main.m
// description
//
// Created by LiuWei on 15/4/15.
// Copyright (c) 2015年 LiuWei. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Teacher.h"
#import "Student.h"
int main()
{
Teacher *t = [[Teacher alloc]init];
// NSLog函数输出信息 格式化字符为 %@, 参数为对象时
// 如果没有重写对象的 -(NSString*)description 方法则默认调用父类的description方法
// 并以此方法返回的NSString*作为 NSLog的参数
// 默认方法输出 <类名: 对象地址>
NSLog(@"没有重写description对象方法: %@", t);
// 如果参数为类时, 且没有重写类方法 +(NSString*)description 方法则默认调用父类的description类方面
// 默认输出 类名
NSLog(@"没有重写description类方法: %@", [t class]);
Student *s = [[Student alloc]init];
s.name = @"Lucy";
s.age = 26;
// 如果重写了对象方法 description NSLog会调用重写之后description方法返回的NSString*做为参数
NSLog(@"重写了description对象方法: %@", s);
NSLog(@"重写了description类方法: %@", [s class]);
return 0;
}