0

在类之外使用 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 集合仍然没有值吗?

4

1 回答 1

2

在 init 中,您首先返回,因此不会分配/实例化字典。将返回移动到方法的末尾。

-(id)init
{
    return [super init]; //!!!!!!!!!!!!

    PaymentMethodSalesTotals = [[ NSMutableDictionary alloc] init];
....
}
于 2010-09-24T11:08:30.347 回答