当在类之外使用类型为NSMutableDictionary的属性时,我无法添加对象。
这是class.h文件
@interface cSummary : NSObject
{
@public
NSMutableDictionary* PaymentMethodSalesTotals;
}
@property (nonatomic, retain) NSMutableDictionary* PaymentMethodSalesTotals;
@end
class.m文件就像这样
#import "cSummary.h"
@implementation cSummary
@synthesize PaymentMethodSalesTotals;
#pragma mark -
#pragma mark Initialisation
-(id)init
{
return [super init];
PaymentMethodSalesTotals = [[ NSMutableDictionary alloc] init];
[PaymentMethodSalesTotals setObject:[NSNumber numberWithFloat:0.0f] forKey:[NSNumber numberWithInt:10]];
[PaymentMethodSalesTotals setObject:[NSNumber numberWithFloat:0.0f] forKey:[NSNumber numberWithInt:20]];
[PaymentMethodSalesTotals setObject:[NSNumber numberWithFloat:0.0f] forKey:[NSNumber numberWithInt:30]];
}
#pragma mark -
#pragma mark Memory management
- (void)dealloc
{
if (PaymentMethodSalesTotals != nil)
[PaymentMethodSalesTotals release];
[super dealloc];
}
@end
然后在另一个类中使用它
cSummary* oSummary = [[cSummary alloc] init];
NSNumber* numPrice = [NSNumber numberWithFloat:150.0f];
[oSummary.PaymentMethodSalesTotals setObject:numPrice forKey:[NSNumber numberWithInt:10]];
如果我在调试中查看这个,那么PaymentMethodSalesTotals集合中仍然没有值?
答案 0 :(得分:2)
在init中,您首先返回,以便不分配/实例化字典。将返回值移动到方法的末尾。
-(id)init
{
return [super init]; //!!!!!!!!!!!!
PaymentMethodSalesTotals = [[ NSMutableDictionary alloc] init];
....
}