【问题标题】:Objective-C NSMutableDictionary DisappearingObjective-C NSMutableDictionary 消失
【发布时间】:2011-01-27 08:28:19
【问题描述】:

我在没有出现值的 NSMutableDictionary 上遇到了这个问题。 我的代码片段如下所示:

//将数据放入Hash,再放入数组

yellowPages = [[NSMutableArray alloc] init];


 NSMutableDictionary *address1=[[NSMutableDictionary alloc] init];
 [address1 setObject:@"213 Pheasant CT" forKey: @"Street"];
 [address1 setObject:@"NC" forKey: @"State"];
 [address1 setObject:@"Wilmington" forKey: @"City"];
 [address1 setObject:@"28403" forKey: @"Zip"];
 [address1 setObject:@"Residential" forKey: @"Type"];

 [yellowPages addObject:address1];


 NSMutableDictionary *address2=[[NSMutableDictionary alloc] init];
 [address1 setObject:@"812 Pheasant CT" forKey: @"Street"];
 [address1 setObject:@"NC" forKey: @"State"];
 [address1 setObject:@"Wilmington" forKey: @"City"];
 [address1 setObject:@"28403" forKey: @"Zip"];
 [address1 setObject:@"Residential" forKey: @"Type"];

 [yellowPages addObject:address2];

 //Iterate through array pulling the hash and insert into Location Object
 for(int i=0; i<locationCount; i++){
  NSMutableDictionary *anAddress=[theAddresses getYellowPageAddressByIndex:i];

  //Set Data Members
  Location *addressLocation=[[Location alloc] init];
  addressLocation.Street=[anAddress objectForKey:@"Street"];
  locations[i]=addressLocation;
  NSLog(addressLocation.Street);

 }

所以问题只是打印了第二个地址,即 813,我不知道为什么。任何人都可以提供任何帮助吗?

【问题讨论】:

    标签: iphone objective-c memory-management nsmutablearray nsmutabledictionary


    【解决方案1】:

    这是一个错字。您总是将值分配给 Address1 字典。

    【讨论】:

      【解决方案2】:

      Laurent 的答案是正确的,您分配给了一个不正确的对象。

      就我个人而言,我在编写代码时会尽量减少可变对象。例如,您正在创建可变字典的地址并将它们存储在可变数组中。就个人而言,我会为地址使用不可变的字典。填充每个地址需要更多代码,但您可以将其重构为另一种方法。关键是,而不是更改地址。作为副作用,编译器会发现您的拼写错误,因为您一直在尝试更改不可变对象。

      实际上,创建一个地址类可能比仅仅填充一个 NSDictionary 更好。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多