【发布时间】:2012-02-05 15:05:01
【问题描述】:
我有一个 mySQL 数据库和一个 php 脚本,它从所述数据库返回一个表的内容。我将这些数据作为字符串保存,并且能够将其放入数组中,但我不太确定如何将其放入自定义 NSObject 类中。有什么办法可以做到吗?
【问题讨论】:
标签: mysql ios arrays json class
我有一个 mySQL 数据库和一个 php 脚本,它从所述数据库返回一个表的内容。我将这些数据作为字符串保存,并且能够将其放入数组中,但我不太确定如何将其放入自定义 NSObject 类中。有什么办法可以做到吗?
【问题讨论】:
标签: mysql ios arrays json class
如果您的字符串是 JSON 对象数组,您可以使用 SBJsonParser 方法 objectWithString:,它将返回 NSDictionary 对象的 NSArray。然后您可以遍历您的数组并从数组中的每个元素创建一个自定义对象。使用 NSDictionary 方法objectForKey: 提取每个值。
SBJsonParser *json = [[SBJsonParser new] autorelease];
NSError *jsonError = nil;
NSArray *parsedJSON = [json objectWithString:response error:&jsonError];
// this example just creates a custom object from the first element in the array
NSDictionary dictionary = [parsedJSON objectAtIndex:0]
CustomObject *myCustomObject = [[CustomObject alloc] init];
myCustomObject.firstname = [dictionary objectForKey:@"firstname"];
myCustomObject.lastname = [dictionary objectForKey:@"lastname"];
【讨论】:
NSLog(@"EVENT NAME: %@",[dictionary objectForKey:@"eventName"]); 时,我返回(空)。我正在异步获取请求,因此认为它可能没有时间获取数据。如果我将其更改为同步,则应用程序会因[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x6b1f8b0' 而崩溃。有什么想法吗?
objectWithString: 将改为返回一个 NSDictionary 对象,您首先需要从该对象提取数组。
{"eventsInfo":[{"eventID":"4","eventName":"Pop Tarts","eventAddress":"Students Union, Sheffield","eventPrice":"5","eventTime":"21:00:00","eventRating":"3","eventLogo":null},{"eventID":"5","eventName":"Space","eventAddress":"Octagon, SU, Sheffield","eventPrice":"4","eventTime":"21:00:00","eventRating":"5","eventLogo":null}]}
NSArray *parsedJSON = [(NSDictionary*)[json objectWithString:response error:&jsonError] objectForKey:@"eventsInfo"];