1

データベースからデータを読み取る iPad がありSQLます。次のコードは問題なく動作し、各レコードから 2 つのフィールドを取得して、NSArray.

5 つのフィールドを読み取る必要がありますが、PHP を介して 5 つの個別のクエリを実行するよりも、それを行うためのより良い方法があると思わずにはいられません (別のフィールドを選択するように設定された Choice パラメータを含む 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 に答える