【问题标题】:Print dictionary in objective c在目标 c 中打印字典
【发布时间】:2012-12-18 20:55:08
【问题描述】:

我无法打印我的数组,我不明白我的问题是什么

在班里我有

@property (nonatomic,strong) NSMutableDictionary *accounts;

在银行开户的VOID功能:

-(void)createAccount{
    int x=random()%10;
    NSString *keys=[NSString stringWithFormat:@"%i",x];
    Account *new_account=[[Account alloc]initWithAccountNum:x];
    [self.accounts setObject:new_account forKey:keys];
}

在我的班级帐户中

@property int num;
@property int plus;

和方法:

-(id)initWithAccountNum:(int)_num{
    self=[self init];
    if(self!=nil){
        self.num=_num;
        self.plus=0;
    }
    return self;
}

-(NSString*)printer{
    return [NSString stringWithFormat:@"Account num=%i plus=%i",self.num,self.plus];
 }

我尝试将数据打印到 Nslog i 主文件:

Bank *bank=[[Bank alloc]init];
[bank createAccount];

for (Account *acc in bank.accounts) {
    Account *printed_account=[bank.accounts objectForKey:acc];
    NSLog(@"%@",printed_account.printer);

}

【问题讨论】:

  • 你是在Bank的init中初始化self.accounts还是nil?
  • 仅将 for 内容替换为 NSLog(@"%@",acc)。将 -printer 方法签名替换为 -(NSString*) description

标签: objective-c dictionary for-in-loop


【解决方案1】:

bank.accounts 应该在你尝试使用它之前分配和初始化。

self.accounts = [[NSMutableDictionary alloc] init];

附录:

要影响 NSLog 为对象打印的内容,您可以覆盖 description

所以你的Account 应该是这样的:

-(NSString*)description{
    return [NSString stringWithFormat:@"Account num=%i plus=%i",self.num,self.plus];
}

NSMutableDictionary已经对格式有很好的描述了:

2013-01-04 12:03:11.405 AppName[19683:c07] {
    key1 = value1;
    key2 = value2;
}

因此您可以将循环简化为:NSLog(@"%@", bank.accounts);

【讨论】:

  • 我在输出中没有任何内容我将函数“createAccount”更改为 Nsstring,在主 NSlog 中我看到了新帐户
  • NSLog(@"%@", bank.accounts); 至少会打印出 (null),如果您甚至没有看到该声明。
  • 那么你需要在Bank init中初始化accountsself.accounts = [[NSMutableArray alloc] init]
  • 对不起,谢谢大家。我是目标c的新手。我忘了这样做:self.accounts=[[NSMutableDictionary alloc]init];
  • 不用谢。通过单击答案旁边的小 ✓ 来接受正确的答案,并可选择对它们进行投票
猜你喜欢
  • 2013-11-07
  • 1970-01-01
  • 2015-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多