[英]description method is not getting called
I created example to learn some basics in objective-c. 我创建了示例,以学习Objective-C的一些基础知识。 I have a class called Person as shown below.
我有一个名为Person的类,如下所示。 in the main method I try to call
description
method to print some data, and AFAIK, description method
is similar to toString
in java..but description
method I created is not called 在主要方法中,我尝试调用
description
方法来打印一些数据,并且AFAIK, description method
类似于java ..中的toString
,但是我创建的description
方法未调用
please have a look at the code below and let me know why the contents of description
method is not called. 请看下面的代码,让我知道为什么不调用
description
方法的内容。
person.h 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 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
main : 主要 :
#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]));
}
}
You might have the call to description
method, but you aren't getting the log message. 您可能已经调用了
description
方法,但没有收到日志消息。 Problem is in the NSString
that you produced. 问题出在您生成的
NSString
中。 This is not valid: 这是无效的:
NSString *desc = @("my age is: %i and my weight is: %i", age, weight);
Try changing this to: 尝试将其更改为:
NSString *desc = [NSString stringWithFormat:@"my age is: %i and my weight is: %i", age, weight];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.