我的应用程序使用NSTask启动Python,然后脚本通过NSPipe返回一个数组。我读取数据,将其放入字符串中,并显示出来:
NSMutableData *data = [[NSMutableData alloc] init];
NSData *readData;
while ((readData = [readHandle availableData])&& [readData length]) {
[data appendData: readData];
}
NSString *string = [[NSString alloc]
initWithData: data
encoding: NSUTF8StringEncoding];这一切都很好,但我意识到我真的需要把它作为一个数组-而不是一个字符串。我找不到从数据(从NSPipe返回的数据)启动数组的方法。我怎么能这么做?我发现的最接近的事情可能是使用:
[NSPropertyListSerialization dataWithPropertyList:format:options:error:]
..。但我不需要“财产清单”本身。我必须先将数据转换为plist吗?
编辑:我刚刚意识到它比我想象的要复杂得多。Python返回一个字典数组,字典中有字符串。这些字符串可以有逗号和其他字符,所以我不认为我可以使用",“分隔符来拆分它。
在Python中:
msg_set = []
msg_set = [
dict(mts="t,s1", mfrom="f@ro,m1", msbj="msb,j1", mbody="bod,y1", mid="i,d1"),
dict(mts="ts2", mfrom="from2", msbj="msb,j2", mbody="body2", mid="id2")
]
print msg_set # <- this is what python returns发布于 2012-08-21 15:40:02
您可以首先将数据转换为JSON (我在dasblinkenlight的答案上看到了注释,但我已经键入了答案),然后将它们传递给Cocoa。就像这样:
Python侧
import json
#...
json.dumps(msg_set) # <- return this one instead目标-C侧
NSString *myPythonJson = @""; // <- Whatever you got from python
NSError *error = nil;
id myObjectsFromJson = [NSJSONSerialization JSONObjectWithData:[myPythonJson dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&error];发布于 2012-08-21 14:56:53
如果返回的数据表示带有分隔符的数组,例如逗号@",",则可以将字符串拆分为数组,如下所示:
NSString *string = [[NSString alloc]
initWithData: data
encoding: NSUTF8StringEncoding];
NSArray *array = [string componentsSeparatedByString:@","];您需要使用与发送端相同的分隔符。如果可以使用多个字符作为分隔符,则可能需要使用componentsSeparatedByCharactersInSet::
NSArray *array = [string componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];https://stackoverflow.com/questions/12057620
复制相似问题