【问题标题】:ObjC : NSLog a pointer nameObjC : NSLog 一个指针名
【发布时间】:2012-11-30 23:40:13
【问题描述】:

我用我创建的 3 个类实例填充了一个 NSMutableArray。现在我想迭代这个数组来获取一些变量值。我可以这样做,但无法打印我的实例名称(面包、水……)相反,我得到了他们的地址。 我想这很简单,但我有点挣扎,所以如果有人知道如何...... 谢谢

#import <Foundation/Foundation.h>
#import "StockHolding.h";

int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

StockHolding *bread = [[StockHolding alloc] init];
[bread setPurchaseSharePrice:100];
[bread setCurrentSharePrice:120];
[bread setNumberOfShares:100];

StockHolding *water = [[StockHolding alloc] init];
[water setPurchaseSharePrice:100];
[water setCurrentSharePrice:80];
[water setNumberOfShares:10];

StockHolding *tomatoes = [[StockHolding alloc] init];
[tomatoes setPurchaseSharePrice:100];
[tomatoes setCurrentSharePrice:50];
[tomatoes setNumberOfShares:1];

NSMutableArray *myStock = [NSMutableArray arrayWithObjects:bread, water, tomatoes, nil];

for (StockHolding *s in myStock)
{
    NSLog(@"Here is what I paid for my %p : %f", s, [s costInDollars]);
    NSLog(@"Here is what I earn for my %p : %f", s, [s valueInDollars]);

}

[pool drain];
return 0;

}

【问题讨论】:

  • costInDollars & valueInDollars 的数据类型是什么。尝试将其打印为字符串。

标签: objective-c class pointers instance nslog


【解决方案1】:

为什么不在 StockHolding 类上实现 -(NSString *)description 方法?然后你可以使用字符串格式的%@,它会在那里输出描述。

您也可以使用%@ 输出StockHolding 实例的任何其他字符串属性。

【讨论】:

    【解决方案2】:

    如果你想 NSLog 一个对象和它的指针名称,你可以在你的预处理器宏中添加这个#define #define OLog(x) NSLog(@"%s = %@",#x, x);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-15
      • 1970-01-01
      • 1970-01-01
      • 2011-05-10
      • 1970-01-01
      • 2014-08-13
      相关资源
      最近更新 更多