Objective C在NSMutableDictionary中访问NSMutableDictionary

时间:2015-02-11 18:48:15

标签: objective-c object nsmutabledictionary

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

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

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属性“检测”并修改它?

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

2 个答案:

答案 0 :(得分:1)

您可以通过提供与词典中的键匹配的键来取回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];

答案 1 :(得分:1)

看起来您必须拥有网络ID和信标ID才能到达您需要的位置。它看起来像是:

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

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

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