[英]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.