在目标c中将字符串转换为结构

问题描述

| 我有这个字符串
a:10,b:xx,e:20,m:xy,w:30,z:50
但是,键和值改变了... 我想将其转换为Objective-C中的结构 (我希望应用程序将字符串自动转换为结构,而不是手动) 在PHP中,结果将是:
 $array = array(
      \'a\' => 10,// or \'a\' => \"10\" (doesn\'t matter)
      \'b\' => \"xx\",\'e\' => 20,// or \'e\' => \"20\" (doesn\'t matter)
      \'m\' => \"xy\",\'w\' => 30,// or \'w\' => \"30\" (doesn\'t matter)
      \'z\' => 50  // or \'z\' => \"50\" (doesn\'t matter)
 );
因此,如何将字符串转换为结构并获得类似于PHP示例中的结果,但要在Objective-C ...中进行呢? 请告诉我确切的代码,我是不是Objective-c的新手:) 谢谢     

解决方法

        PHP结构对我来说更像是一本字典,所以我将假设它是。
NSString *s = @\"a:10,b:xx,e:20,m:xy,w:30,z:50\";
NSArray *pairs = [s componentsSeparatedByString:@\",\"];
NSMutableArray *keys = [NSMutableArray array];
NSMutableArray *values = [NSMutableArray array];

for (NSString *pair in pairs)
{
    NSArray *keyValue = [pair componentsSeparatedByString:@\":\"];
    [keys addObject:[keyValue objectAtIndex:0]];
    [values addObject:[keyValue objectAtIndex:1]];
}

NSDictionary *dict = [NSDictionary dictionaryWithObjects:values forKeys:keys];
NSLog(@\"%@\",dict);
那显然是很冗长的,但是需要一些花哨的字符串操作。 输出如下:
{
    a = 10;
    b = xx;
    e = 20;
    m = xy;
    w = 30;
    z = 50;
}
    ,        您可以分解字符串,再次分解片段,然后将所有内容放入字典中。这应该工作:
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
NSString *str = @\"a:10,z:50\";
NSArray *arr = [str componentsSeparatedByString:@\",\"];
for (NSString *fragment in arr) {
    NSArray *keyvalue = [fragment componentsSeparatedByString:@\":\"];
    [dict setObject:[keyvalue objectAtIndex:0] forKey:[keyvalue objectAtIndex:1]];
}
    ,        
NSString* myString = @\"a:10,z:50\";
使用下面的NSString方法。
- (NSArray *)componentsSeparatedByString:(NSString *)separator
NSArray* myArray = [myString componentsSeparatedByString:@\",\"];
NSMutableDictionary *myDictionary = [NSMutableDictionary dictionary];
for (NSString* stringObj in myArray) 
{
     NSArray *myTemp1 = [stringObj componentsSeparatedByString:@\":\"];
    [myDictionary setObject:[myTemp1 objectAtIndex:0] forKey:[myTemp1 objectAtIndex:1]];
}
现在myDictionary实例等效于$ array