从SQL数据库读入NSArray

时间:2013-07-28 10:30:27

标签: sql objective-c nsarray

我有一台iPad从SQL数据库中读取数据。以下代码工作正常,从每个记录中检索2个字段并将其读入NSArray

我现在需要阅读5个字段,我不禁认为有更好的方法,而不是通过php运行5个单独的查询(getinfo.php文件,选择参数设置为选择不同的领域)。

指向更好的方法的任何指针?

NSString *strURLClass = [NSString stringWithFormat:@"%@%@", @"http://wwwaddress/getinfo.php?choice=1&schoolname=",obsSchoolName];
NSArray *observationsArrayClass = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL URLWithString:strURLClass]];
observationListFromSQL = [[NSMutableArray alloc]init];
NSEnumerator *enumForObsClass = [observationsArrayClass objectEnumerator];

NSString *strURLDate = [NSString stringWithFormat:@"%@%@", @"http://wwwaddress/getinfo.php?choice=5&schoolname=",obsSchoolName];
NSArray *observationsArrayDate = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL URLWithString:strURLDate]];
observationListFromSQL = [[NSMutableArray alloc]init];
NSEnumerator *enumForObsDate = [observationsArrayDate objectEnumerator];

id className, dateOfObs;

while (className = [enumForObsClass nextObject])
{
    dateOfObs = [enumForObsDate nextObject];
    [observationListFromSQL addObject:[NSDictionary dictionaryWithObjectsAndKeys:className, @"obsClass", dateOfObs, @"obsDate",nil]];
}

1 个答案:

答案 0 :(得分:1)

是的,您可以通过将语句“折叠”到循环中并使用可变字典来减少代码:

// Add other items that you wish to retrieve to the two arrays below:
NSArray *keys = @[@"obsClass", @"obsDate"]; // Key in the dictionary
NSArray *choices = @[@1, @5];               // Choice in the URL string
NSMutableArray *res = [NSMutableArray array];
NSMutableArray *observationListFromSQL = [NSMutableArray array];
for (int i = 0 ; i != keys.count ; i++) {
    NSNumber *choice = choices[i];
    NSString *strURLClass = [NSString stringWithFormat:@"http://wwwaddress/getinfo.php?choice=%@&schoolname=%@", choice, obsSchoolName];
    NSArray *observationsArray = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL URLWithString:strURLClass]];
    NSEnumerator *objEnum = [observationsArrayClass objectEnumerator];
    NSString *key = keys[i];
    NSMutableDictionary *dict;
    if (res.count < i) {
        dict = res[i];
    } else {
        dict = [NSMutableDictionary dictionary];
        [res addObject:dict];
    }
    id item;
    while (item = [objEnum nextObject]) {
        [res setObject:item forKey:key];
    }
}