NSArray objectAtIndex不起作用。请帮忙

时间:2010-06-23 14:00:14

标签: cocoa iphone-sdk-3.0 nsstring nsarray appkit

NSArray* address = [NSArray arrayWithArray:[detailItem addressArray]];
NSLog(@"address = %@", address);
NSString* addressToString = @"";
int arrayCount = [address count];
for (int i = 0; i < arrayCount; i++) {
    addressToString = [addressToString stringByAppendingString:[address objectAtIndex:i]];
    if (i == arrayCount -1) {
        addressToString = [addressToString stringByAppendingString:@""];
    } else {
        addressToString = [addressToString stringByAppendingString:@", "];
    }       
}

地址是一个持有地址的NSArray

2010-06-23 09:05:19.346 iPhoneExample[1093:207] address = (
        {
        City = "Cupertino";
        Country = "United States";
        CountryCode = us;
        State = CA;
        Street = "1 Infinite Loop";
        ZIP = 95014;
    }
)

我正试图通过数组并创建一个CSV字符串,因此它看起来像

Cupertino, "United States", us, CA, "1 Infinite Loop", 95014

然而,我一直在崩溃

addressToString = [addressToString stringByAppendingString:@", "];

我收到的消息是

 *** -[NSCFDictionary stringByAppendingString:]: unrecognized selector sent to instance 0x1c2f10

更新: detailItem是ABContact类型的对象(自定义类)。

ABContact有一个名为addressArray

的属性
@property (nonatomic, readonly) NSArray *addressArray;

我的addressArray的定义是

- (NSArray *) addressArray {return [self arrayForProperty:kABPersonAddressProperty];}

3 个答案:

答案 0 :(得分:3)

您的“地址”是NSDictionary的NSArray,而不是NSArray的NSArray。

要将字典的值作为数组获取,可以使用

[theDictionary allValues]

但订单上有 no 保证。我认为你真正需要的是:

NSMutableString* addressToString = [NSMutableString string];  // use mutable string!
for (NSDictionary* item in address) {     // use fast enumeration!
  [addressToString appendFormat:@"%@, \"%@\", %@, %@, \"%@\", %@\n",
   [item objectForKey:@"City"], 
   /* etc ... */
  ];
}

答案 1 :(得分:1)

此:

2010-06-23 09:05:19.346 iPhoneExample[1093:207] address = (
    {
    City = "Cupertino";
    Country = "United States";
    CountryCode = us;
    State = CA;
    Street = "1 Infinite Loop";
    ZIP = 95014;
}
)

NSDictionary。您需要使用[dictionary objectForKey:'City']

访问其成员

因此,您的更新代码应为:

NSDictionary* address = [detailItem addressArray];
NSLog(@"address = %@", address);
NSString* addressToString = @"";
int counter = 0;
for (id object in myDictionary) {
  if (counter != 0)
    addressToString = [addressToString stringByAppendingString:@","];
  addressToString = [addressToString stringByAppendingString:object];   
  counter++;
}

答案 2 :(得分:0)

如果您可以将addressArray方法更改为实际返回数组而不是字典,那么您可以这样做:

NSString * addressString = [[detailItem addressArray] componentsJoinedByString:@","];

就是这样......