学习笔记(objective-c)-重写description方法
2015-06-14 13:42
686 查看
description方法是一个自我描述的方法。主要是告诉外界该对象所具有的状态信息。
NSObject所提供的description方法一般返回<class:16进制的首地址>,想实现自我描述,必须重写该方法。
例:
#import <Foundation/Foundation.h>
@interface APPLEAnimal : NSObject
@property (nonatomic,copy) NSString* name;
-(id) initWithName:(NSString*) name;
@end
#import "APPLEAnimal.h"
@implementation APPLEAnimal
@synthesize name=_name;
-(id) initWithName:(NSString*) name
{
if(self = [super init])
{
self.name=name;
}
return self;
}
//重写description方法,实现自我描述的功能
-(NSString*) description
{
return [NSString stringWithFormat:@"my name is %@",self.name];
}
@end
int main(int argc,char* argv[])
{
@autoreleasepool{
APPLEAnimal* animal = [[APPLEAnimal alloc]initWithName:@"horse"];
//输出myname is horse
NSLog(@"%@",animal);
}
}
NSObject所提供的description方法一般返回<class:16进制的首地址>,想实现自我描述,必须重写该方法。
例:
#import <Foundation/Foundation.h>
@interface APPLEAnimal : NSObject
@property (nonatomic,copy) NSString* name;
-(id) initWithName:(NSString*) name;
@end
#import "APPLEAnimal.h"
@implementation APPLEAnimal
@synthesize name=_name;
-(id) initWithName:(NSString*) name
{
if(self = [super init])
{
self.name=name;
}
return self;
}
//重写description方法,实现自我描述的功能
-(NSString*) description
{
return [NSString stringWithFormat:@"my name is %@",self.name];
}
@end
int main(int argc,char* argv[])
{
@autoreleasepool{
APPLEAnimal* animal = [[APPLEAnimal alloc]initWithName:@"horse"];
//输出myname is horse
NSLog(@"%@",animal);
}
}
相关文章推荐
- WebSocket使用javax.websocket.RemoteEndpoint.Basic.sendObject(Object arg0)向页面方法发送对象
- java笔记10 多态 Object类
- UGUI - 判断是否点击在UI 上 Bug,IsPointerOverGameObject()在移动端检测失败
- ObjectOutStream的reset方法
- 学习笔记(objective-c)-判断指针变量的实际类型
- Python标准库:内置函数vars([object])
- Python标准库:内置函数vars([object])
- 学习笔记(objective-c)-多态
- 【ObjectC】oc中的内存分配
- error: while loading shared libraries : countlib.so : cannnot open shared object file : No such fil
- Faq_flask : AttributeError: ‘module’ object has no attribute ‘autoescape’
- Objective-C语法之扩展(Extension)的使用
- Objective-C语法之字符串NSString去掉前后空格或回车符(可以是NSCharacterSet类型的其它字符)
- Objective-C语法之可变参数
- Objective-C语法之NSDictionary和NSMutableDictionary
- Objective-C语法之指针型参数
- Objective-C语法之nonatomic和atomic之间的区别
- Objective-C语法之NSSortDescriptor
- Objective-C语法之NSPredicate的使用
- jsrender for object