objective-c - NSDictionary 返回键的空值

标签 objective-c ios xcode

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

相关文章:

ios - Objective-C 或 Swift 中的 Jaro Winkler 距离

ios - iOS录音时如何将PCM缓存实时转为AAC数据?

iOS 如何在数组解析Swift中从数据库下载数据

iphone - respondsToSelector 发送到释放的对象

xcode - OS X Notification Center 中的 ListView

ios - 在 iOS 10 中使用标签栏 Controller 时, Collection View 的高度计算错误

iOS 前缀文件 : Including NSManagedObjects (Core Data generated classes)

ios - XCode 5 GM 链接器错误 : too many compact unwind infos in function anon for architecture i386

ios - 需要生成的 JSON 文档与 iOS 中 NSMutableDictionary 中插入的对象的顺序相同

c# - Microsoft.ML 和 Xamarin