我无法理解为什么以下代码在控制台/终端中显示“ The First Key =(null)”:

这是接口:

#import <UIKit/UIKit.h>

@interface TestingViewController : UIViewController

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

@end


这是实现:

#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


提前致谢!

最佳答案

您尚未分配字典。现在是nil,向nil发送消息没有任何作用。

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

self.myDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil];


如果不是这样

self.myDictionary = [[[NSDictionary alloc] initWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil] autorelease];

关于objective-c - NSDictionary返回键的空值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9423131/

10-12 06:29