我无法理解为什么以下代码在控制台/终端中显示“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/