我创建了一个NSMutableDictionary
以及一个向字典中添加对象的方法。我知道函数addObject正确地将对象添加到字典中,但是稍后当我尝试使用方法Print_Object
打印对象时,属于对象的每个变量都打印为null/0
。我的代码有问题吗?
-(NSMutableDictionary *)_stock{
if (!_stock) {
_stock = [[NSMutableDictionary alloc]init];
}
return _stock;
}
-(void) addObject:(NSString*) desc key: (NSString*) theKey floatrc: (float) retailcost floatwsc: (float) wholesalecost intnoh: (int) numonhand floatns: (int) numsold {
object_info* obj = [[object_info alloc]init];
[obj setDescription: desc];
[obj setRetailCost: retailcost];
[obj setWholeSaleCost:wholesalecost];
[obj setNumOnHand: numonhand];
[obj setNumItemsSold: numsold];
[self.stock setValue:obj forKey:theKey];
}
-(void) Print_Object:(NSString *) theKey {
object_info* obj = [self.stock objectForKey:theKey];
NSLog(@"Key: %@ Description: %@ Retail Cost: %f Wholesale Cost: %f Number on Hand: %i Number Sold: %i", theKey, obj.description, obj.retail_cost, obj.wholesale_cost, obj.num_on_hand, obj.num_items_sold);
}
这是object_info的声明:
#import "object_info.h"
@implementation object_info
//Getters
-(NSString *)description {
return description;
}
-(float) retail_cost {
return retail_cost;
}
-(float) wholesale_cost {
return wholesale_cost;
}
-(int) num_on_hand {
return num_on_hand;
}
-(int) num_items_sold {
return num_items_sold;
}
//Setters
-(void)setDescription:(NSString *) value {
description = value;
}
-(void) setRetailCost: (float) n {
retail_cost = n;
}
-(void) setWholeSaleCost: (float) n {
wholesale_cost = n;
}
-(void) setNumOnHand: (int) n {
num_on_hand = n;
}
-(void) setNumItemsSold: (int) n {
num_items_sold = n;
}
@end
这是object_info.h:
#import <Foundation/Foundation.h>
@interface object_info : NSObject
{
NSString *description;
float retail_cost;
float wholesale_cost;
int num_on_hand;
int num_items_sold;
}
-(NSString *)description;
-(void)setDescription:(NSString *)value;
-(float) retail_cost;
-(void) setRetailCost:(float) n;
-(float) wholesale_cost;
-(void) setWholeSaleCost:(float) n;
-(int) num_on_hand;
-(void) setNumOnHand: (int) n;
-(int) num_items_sold;
-(void) setNumItemsSold:(int) n;
@end
答案 0 :(得分:0)
您能告诉我们stock
的声明吗?我怀疑你已将其声明为@property
,在这种情况下,您尝试将-_stock
声明为getter将无效。实例变量将为_stock
,但getter将仅为-stock
。如果这是一个正确的猜测,那么您是NSLog(@"%@", self.stock)
您应该看到(null)
作为输出 - 您的自定义getter未被调用,因此不会创建任何字典。
您的代码通常看起来很老套;特别是:
@interface
内;把它放在@implementation
; object_info
可以重新表述为@property
,然后您无需在@implementation
内部实现内容,只需允许属性自动合成; [obj setDescription: desc];
等,您现在通常会看到使用点语法,例如obj.description = desc;
。编译器仍然会确保调用正确的setter(或getter),它只是一个需要较少心理上下文的表达式,允许直接从左到右读取; dictionary[key] = value
存储和dictionary[key]
访问。答案 1 :(得分:0)
[self addObject:@"AAA" key:@"BBB" floatrc:100 floatwsc:200 intnoh:300 floatns:400];
[self Print_Object:@"BBB"];
这对我来说很好,你用错了钥匙吗?
[self addObject:@"AAA" key:@"BBB" floatrc:100 floatwsc:200 intnoh:300 floatns:400];
[self Print_Object:@"AAA"];
这是错误的,因为该对象为零。
2017-02-16 10:48:34.086 Test[53298:14250944] Key: AAA Description: (null) Retail Cost: 0.000000 Wholesale Cost: 0.000000 Number on Hand: 0 Number Sold: 0