代码之家  ›  专栏  ›  技术社区  ›  user2121

未调用描述方法

  •  0
  • user2121  · 技术社区  · 7 年前

    description 方法打印一些数据,然后AFAIK, description method toString 在java中..但是 未调用我创建的方法

    请看一下下面的代码,让我知道为什么

    #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
    

    人.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]));
        }
    }
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   nayem    7 年前

    你可以打电话给 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];