繁体   English   中英

描述方法没有被调用

[英]description method is not getting called

我创建了示例,以学习Objective-C的一些基础知识。 我有一个名为Person的类,如下所示。 在主要方法中,我尝试调用description方法来打印一些数据,并且AFAIK, description method类似于java ..中的toString ,但是我创建的description方法未调用

请看下面的代码,让我知道为什么不调用description方法的内容。

person.h

#import <Foundation/Foundation.h>

@interface Person : NSObject {
    int age;
    int weight;
}

-(void) setAge:(int) age;
-(void) setWeight: (int) weight;

-(int) getAge;
-(int) getWeight;

-(NSString *) description;

@end

person.m

#import "Person.h"

@implementation Person

-(void) setAge:(int) a {
    age = a;
}

-(void) setWeight:(int) w {
    weight  = w;
}

-(int) getAge {
    return age;
}

-(int) getWeight {
    return weight;
}

-(NSString *) description {
    NSString *desc = @("my age is: %i and my weight is: %i", age, weight);
    NSLog(@"%@", desc);
    return desc;
}
@end

主要

#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#import "Person.h"

int main(int argc, char * argv[]) {
    @autoreleasepool {

        Person *me = [[Person alloc] init];

        [me setAge:20];
        [me setWeight:55];

        NSString *desc = [me description];
        NSLog(@"%@", desc);

        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}

您可能已经调用了description方法,但没有收到日志消息。 问题出在您生成的NSString中。 这是无效的:

NSString *desc = @("my age is: %i and my weight is: %i", age, weight);

尝试将其更改为:

NSString *desc = [NSString stringWithFormat:@"my age is: %i and my weight is: %i", age, weight];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM