1

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

在班银行我有

@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);

}
4

1 回答 1

3

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);

于 2013-01-04T12:05:23.150 回答