我的Objective-C经验不好,如果有人可以帮助我,我会很乐意。

周围还有其他一些代码,但我相信我已将其简化为问题所在。我想做的是用一个键保存一个双精度(包装到NSNumber中),下面是我的代码:

。H

@interface MyClass : something
{
    MyMap* usemap;
}
@end

@interface MyMap : something
@property (atomic, strong) NSMutableDictionary* mmap;
@end


.m

@implementation MyMap
@class MyClass;
NSMutableDictionary* mmap = [[NSMutableDictionary alloc] init];
@end

@implementation MyClass
MyMap* usemap = [MyMap alloc];

//-void { switch() { case x:
NSString* key = @"testkey";
NSNumber* value = [NSNumber numberWithDouble:1];
NSLog(@"Saving value: %@ to key: %@",value,key);
[usemap.mmap setObject:value forKey:key];
NSNumber* get = [usemap.mmap objectForKey:key];
NSLog(@"Saved value: %@ to key: %@",get,key);


现在打印:

Saving value: 1 to key: testkey

Saved value: (null) to key: testkey


我想念什么?它应该已经保存了双精度数字“ 1”。

最佳答案

您需要重写MyClass init方法并在其中usemap = [[MyMap alloc] init]初始化MyMap。然后覆盖MyMap的init方法,并在其中self.mmap = [[NSMutableDictionary alloc] init]初始化mmap。

在MyClass覆盖的init方法中完成其余工作。这是一个粗略的草图:

。H

@interface MyClass : something
{
    MyMap* usemap;
}
@end

@interface MyMap : something
@property (atomic, strong) NSMutableDictionary* mmap;
@end


.m

@implementation MyMap
@class MyClass;

- (instancetype)init {
    if ((self = [super init]))
        self.mmap = [[NSMutableDictionary alloc] init];

    return self;
}

@end

@implementation MyClass

- (instancetype)init {

        if ((self = [super init]))
        {
              usemap = [[MyMap alloc] init];

              NSString* key = @"testkey";
              NSNumber* value = [NSNumber numberWithDouble:1];
              NSLog(@"Saving value: %@ to key: %@",value,key);
              [usemap.mmap setObject:value forKey:key];
              NSNumber* get = [usemap.mmap objectForKey:key];
              NSLog(@"Saved value: %@ to key: %@",get,key);
       }

   return self;
}
@end


希望能帮助到你!

关于ios - 无法使NSMutableDictionary工作(xcode),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41779367/

10-09 09:15