2011-05-31 45 views
0

我有这个字符串a:10,b:xx,e:20,m:xy,w:30,z:50转换刺在Objective-C构建

但是,我想将其转换为结构在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 :)

谢谢

回答

2

这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; 
} 
+0

这就是为什么我讨厌的Objective-C。对于来自PHP的每个人来说真的很痛苦 – dynamic 2011-05-31 12:27:49

+0

字符串操作不是Objective-C的强项(除了支持Unicode支持比其他选择更好)。去任何语言将是一种'痛苦'。但它关于使用正确的工具来完成这项工作。但在iOS上时,它是大多数工作的唯一(理智)工具。 – 2011-05-31 12:45:39

+0

它不仅是字符串。做几乎所有你需要的如此慷慨,如果你不习惯你会很快生气 – dynamic 2011-05-31 12:55:57

1

您可以爆炸的字符串,再次爆炸的碎片,并把所有的成字典。这应该工作:下面的NSString的方法

NSMutableDictionary *dict = [NSMutableDictionary dictionary]; 
NSString *str = @"a:10,b:xx,e:20,m:xy,w:30,z:50"; 
NSArray *arr = [str componentsSeparatedByString:@","]; 
for (NSString *fragment in arr) { 
    NSArray *keyvalue = [fragment componentsSeparatedByString:@":"]; 
    [dict setObject:[keyvalue objectAtIndex:0] forKey:[keyvalue objectAtIndex:1]]; 
} 
+0

谢谢... :) – Andy 2011-05-31 11:33:18

1
NSString* myString = @"a:10,b:xx,e:20,m:xy,w:30,z:50"; 

使用。

- (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例如相当于$阵列

+0

谢谢... :) – Andy 2011-05-31 11:33:47