I created example to learn some basics in objective-c. I have a class called Person as shown below. 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
please have a look at the code below and let me know why the contents of description
method is not called.
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
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. Problem is in the NSString
that you produced. 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];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.