调用时不在子类中计算的数组值

时间:2014-04-09 03:49:52

标签: objective-c

刚刚在BNR iOS书和第2章的挑战中做了一些黄金挑战让我感到难过。

这是我的BNRContainer.m类文件,它是BNRItem的子类。挑战的目的是覆盖对象的描述并打印出它的一些属性。没有正确计算的是BNRContainer containerValue

#import "BNRContainer.h"

... 

-(int)containerValue{

    int total = 0;

    for (BNRItem *item in self.subItems) {
        total += item.valueInDollars;
    }

    return total;
}

-(NSString *)description{


    NSString *descriptionstr = [NSString stringWithFormat:@"I'm a container named %@! My total value is %d and my items are %@",self.itemName, containerValue, self.subItems];
    return descriptionstr;
}

这是Main.m:

#import <Foundation/Foundation.h>
#import "BNRItem.h"
#import "BNRContainer.h"

int main(int argc, const char * argv[])
{

    @autoreleasepool {

        NSMutableArray *items = [[NSMutableArray alloc] init];

        BNRItem *item = [[BNRItem alloc] initWithItemName:@"Red Sofa" valueInDollars:100 serialNumber:@"A1B2C"];
        BNRItem *itemWithName = [[BNRItem alloc] initWithItemName:@"Blue Sofa" valueInDollars:45 serialNumber:NULL];
        BNRItem *itemWithNoName = [[BNRItem alloc]init];

        [items addObject:item];
        [items addObject:itemWithName];
        [items addObject:itemWithNoName];

        BNRContainer *container = [[BNRContainer alloc]init];

        container.itemName = @"TheMainContainer";
        container.subItems = items;

        NSLog(@"%@",container);

        items = nil;

    }
    return 0;
}

我的结果:

2014-04-08 23:38:58.395 RandomItems[83205:303] I'm a container named TheMainContainer! My total value is 0 and my items are (
    "Red Sofa (A1B2C): Worth 100, Recorded on 2014-04-09 03:38:58 +0000",
    "Blue Sofa ((null)): Worth 45, Recorded on 2014-04-09 03:38:58 +0000",
    "Item (): Worth 0, Recorded on 2014-04-09 03:38:58 +0000"

1 个答案:

答案 0 :(得分:0)

那就是...... self

的好旧排除
NSString *descriptionstr = [NSString
                            stringWithFormat:@"I'm a container named %@! My total value is %d and my items are %@",
                            self.itemName,
                            self.containerValue, //self was missing
                            self.subItems];