1

SQL我有一台从数据库读取数据的 iPad 。以下代码工作正常,从每条记录中检索 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]];
}
4

1 回答 1

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];
    }
}
于 2013-07-28T10:49:03.033 回答