NSDictionary为key返回null值

Moo*_*ose 0 xcode objective-c ios

我无法理解为什么以下代码在控制台/终端中显示"第一个键=(null)":

这是界面:

#import <UIKit/UIKit.h>

@interface TestingViewController : UIViewController

@property (nonatomic, strong) NSMutableArray *namesArray;
@property (nonatomic, strong) NSDictionary *myDictionary; 

@end
Run Code Online (Sandbox Code Playgroud)

这是实施:

#import "DictionaryTestViewController.h"

@implementation DictionaryTestViewController

@synthesize namesArray;
@synthesize myDictionary;

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self.myDictionary initWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil];
    NSLog(@"The First Key = %@", [self.myDictionary objectForKey:@"key1"]);
}

@end
Run Code Online (Sandbox Code Playgroud)

提前致谢!

X S*_*ash 5

你还没有分配你的字典.现在是nil这样,向nil发送消息什么都不做.

如果您使用ARC,请将其更改为此

self.myDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil];
Run Code Online (Sandbox Code Playgroud)

如果不是这样的话

self.myDictionary = [[[NSDictionary alloc] initWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil] autorelease];
Run Code Online (Sandbox Code Playgroud)