Objective C 在 NSMutableDictionary 中访问 NSMutableDictionary

Objective C Acessing NSMutableDictionay inside NSMutableDictionary

我是 objective C 的新手,在访问 NSMutableDictionary 时遇到严重问题。

我有两个对象(NetworkBeacon),我想创建一个 NSMutableDictionary 的网络和 NSMutableDictionaryBeacon 的网络里面。

Network.h

#import <Foundation/Foundation.h>

@interface Network : NSObject{
    NSString *id_network;
    NSString *major;
    NSString *active;
    NSString *name;
    NSString *status;
    NSMutableDictionary *beaconsDictionary;
}

@property (nonatomic, strong) NSString *id_network;
@property (nonatomic, strong) NSString *major;
@property (nonatomic, strong) NSString *active;
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *status;
@property (nonatomic, strong) NSMutableDictionary *beaconsDictionary;
@end

Beacon.h

#import <Foundation/Foundation.h>

@interface Beacon : NSObject{
    NSString *id_beacon;
    NSString *major;
    NSString *minor;
    NSString *active;
    NSString *detected;
}

@property (nonatomic, strong) NSString *id_beacon;
@property (nonatomic, strong) NSString *major;
@property (nonatomic, strong) NSString *minor;
@property (nonatomic, strong) NSString *active;
@property (nonatomic, strong) NSString *detected;

@end

我可以这样创建 NSMutableDictionary

    Beacon *beacon = [[Beacon alloc]init];
        beacon.id_beacon=@"1";
        beacon.major=@"1";
        beacon.minor=@"1";
        beacon.active=@"1";
        beacon.detected=@"0";
    NSMutableDictionary *beaconDic = [[NSMutableDictionary alloc]init];
   [beaconDic setObject:beacon forKey:beacon.id_beacon];

    Network *net = [[Network alloc]init];
        net.id_network=@"1";
        net.major=@"1";
        net.active=@"1";
        net.name=@"network 1";
        net.status=@"1";
        net.beaconsDictionary=beaconDic;


    NSMutableDictionary *networkDic = [[NSMutableDictionary alloc]init]; 
  [networkDic setObject:net forKey:net.id_network];

好的,但是现在我怎样才能直接访问 beacon 属性 "detected" 并进行修改?

我知道这是一个非常糟糕的例子,但我不知道该怎么做。

您可以通过提供与字典中的键匹配的键来取回您的 NetworkBeacon 对象:

NSString *nwKey = @"1";
Network *n = networkDic[nwKey];
NSDictionary *bDict = n.beaconsDictionary;
NSString *bnKey = @"1";
Beacon *b = bDict[bnKey];

注意:这是新语法。这是旧的:

NSString *nwKey = @"1";
Network *n = [networkDic objectForKey:nwKey];
NSDictionary *bDict = n.beaconsDictionary;
NSString *bnKey = @"1";
Beacon *b = [bDict objectForKey:bnKey];

看来您必须有一个网络 ID 和一个信标 ID 才能到达您需要去的地方。它看起来像:

Network *net = networkDic[netId];
Beacon *beacon = net.beaconsDictionary[beaconId];
beacon.detected = newDetectedValue;

这是针对任意网络 ID 和信标 ID。如果愿意,您可以对值进行硬编码。

编辑: 在您的示例代码中值得注意的是,您可以使用更现代的字典分配。您可以 dictionary[key] = value; 而不是 [dictionary setValue:value forKey:key];。当然,这是个人喜好,但你很可能会在最近的事情中看到后者,我发现它更清楚。