在objective-c中打印自定义类

- (NSString *)description;是基类NSObject 所带的方法,在自定义的子类中,我们可以重载该方法来实现打印自定义类。

首先,我们可以自定义一个Person类。

@interface Person:NSObject
{
    NSString *name;
}
@end

@implementation Person

-(id) init
{
    if(self=[super init])
    {
        name=@"孙武";
    }
    return self;
}

@end
然后在@implementation中重写- (NSString *)description;方法。
-(NSString *)description
{
    return [NSString stringWithFormat:@"我的名字是: %@",name];
}

使用NSLog输出即可。

    Person *newPerson=[[Person alloc]init];
    NSLog(@"%@",newPerson);

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章