【问题标题】:Convert two NSarray to NSString将两个 NSarray 转换为 NSString
【发布时间】:2020-09-21 19:51:23
【问题描述】:

嗨,我的视图控制器中有两个 NS 数组,它们的计数相同。顺便说一句,这是为了提交上传。

barcodeItems = [[NSMutableArray alloc] init];

barcodeItemsQuantity = [[NSMutableArray alloc] init];

一旦数组被填充,这个方法就会被调用,

-(void) performUploadOperation {
parameters = [NSMutableDictionary dictionary];

// Add barcodes and quantity
if (barcodeItems != nil || barcodeItemsQuantity != nil) {

    [parameters setValue:barcodeItems forKey:@"upc"];
    [parameters setValue:barcodeItemsQuantity forKey:@"upcQuantity"];

   }
}

提交后,将调用另一个方法将其转换为 nsstring

NSArray* upc = [parameters objectForKey:@"upc"];
NSArray* upcQuantity = [parameters objectForKey:@"upcQuantity"];

NSString* sample = [NSString stringWithFormat:@"{\"upc_list\" : { \"%@\": %@}}", upc, upcQuantity];
NSLog(@"%@", sample);

结果是这样的

{"upc_list" : { "(
    76239878,
    0827755090991,
    76239878
)": (
    12,
    23,
    32
)}}

而我想要实现的是这样的。两个数组总是有相同的计数

{"upc_list" : { "
   (
    "76239878" : 12,
    "0827755090991" : 23,
    "76239878" : 32
   )
 }}

【问题讨论】:

  • 我想知道这是否与您上一个问题stackoverflow.com/questions/62151077/… 有某种关系...相同的模式-两个数组,带有字符串键的字典,...上一个问题不是很清楚,而这个也不是。
  • " 调用将其转换为 nsstring":为什么?为什么要这样打印?目标是什么?

标签: ios arrays json objective-c


【解决方案1】:

@jordanzee:您可以使用下面的代码来获得您的预期结果。

NSArray *upc = [parameters objectForKey:@"upc"];
NSArray *upcQuantity = [parameters objectForKey:@"upcQuantity"];

NSMutableDictionary *aMutDict = [NSMutableDictionary dictionary];
for(NSInteger aIndex = 0; aIndex < upc.count; aIndex++){
   [aMutDict setValue:upcQuantity[aIndex] forKey:upc[aIndex]];
}

NSString *sample = [NSString stringWithFormat:@"{\"upc_list\" : %@}", aMutDict];
NSLog(@"%@", sample);

【讨论】:

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