iOS:关于动态创建的数组的查询

时间:2013-11-11 08:44:15

标签: ios nsarray

我从Web服务(我的流程中的Web服务2)获得四个参数 - slno,order,flag,name。我不知道这些参数会被接收多少次。在这四个参数中,我将'name'发送给标签,因为它包含要问的问题。

 NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"some url"]];

        NSLog(@"Web service 2 url is = %@", url);

        NSString *json = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:&error];
        NSLog(@"Json data = %@ \n error = %@", json, error);

        if(!error)
        {
            NSData *jsonData = [json dataUsingEncoding:NSASCIIStringEncoding];
            NSArray *myJsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:Nil];

            //NSArray *arrayLabel = [[NSArray alloc] initWithObjects:label1, label2, label3, label4, label5, label6, nil];

            //NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:myJsonArray.count];
            i = 0;
            for(NSDictionary *myJsonDictionary in myJsonArray)
            {
                //UILabel *label = (UILabel *)[arrayLabel objectAtIndex:i++];
                //[label setText:myJsonDictionary[@"Name"]];

                NSString *name = myJsonDictionary[@"Name"];
                NSLog(@"Question from ws2 is %@", name);

                projectIdGobal = myJsonDictionary[@"ProjectID"];
                NSLog(@"Project id from ws2 is %@", projectIdGobal);

                slno = myJsonDictionary[@"SLNO"];
                NSLog(@"slno from ws2 is %@", slno);

                NSString *idWS2 = myJsonDictionary[@"ID"];
                NSLog(@"id from ws2 is %@", idWS2);

                order = myJsonDictionary[@"Order"];
                NSLog(@"order from ws2 is %@", order);

                flag = myJsonDictionary[@"Flag"];
                NSLog(@"flag from ws2 is %@", flag);

                [self putLabelsInScrollView:name];

                i++;
            }
            NSLog(@"Number of cycles in for-each = %d", i);

                [activity stopAnimating];
        }

- (void) putLabelsInScrollView:(NSString *)labelText
{

            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, yPosition_label, 261, 30)];
            [label setFont:[UIFont fontWithName:@"Helvetica Neue" size:12.0f]];
            label.numberOfLines = 2;
            [label setText:labelText];

            [self.scroll addSubview:label];
            yPosition_label += 90;

            UITextField *text = [[UITextField alloc] initWithFrame:CGRectMake(10, yPosition_text, 261, 30)];
            text.borderStyle = UITextBorderStyleRoundedRect;
            text.textColor = [UIColor blackColor];
            text.font = [UIFont systemFontOfSize:12.0];
            text.backgroundColor = [UIColor clearColor];
            text.keyboardType = UIKeyboardTypeDefault;
            text.delegate = self;
            [self.scroll addSubview:text];
            yPosition_text += 90;
            yPosition_result = yPosition_label + yPosition_text;

        [self.scroll setContentSize:CGSizeMake(self.scroll.frame.size.width, yPosition_result)];
        [self.view addSubview:self.scroll];
    }

现在我创建了一个动态创建的文本字段,并将用户输入的答案存储在数组中,如下所示。

- (IBAction)save:(id)sender {
    NSMutableArray *mutableTextArray = [[NSMutableArray alloc] init];
    for(UITextField *field in self.scroll.subviews)
    {
        if([field isKindOfClass:[UITextField class]])
        {
            if([[field text] length] > 0)
            {
                [mutableTextArray addObject:field.text];
                //NSLog(@"Save button 1 : %@", mutableTextArray);
                //NSString *str = [str stringByAppendingString:[mutableTextArray objectAtIndex:0]];
                //[self fetchStrings:mutableTextArray];
            }
        }
    }

    NSLog(@"Save button 2 : %@", mutableTextArray);
    [self fetchStrings:mutableTextArray];
}

现在,在将答案发布到另一个Web服务(我的流程中的Web服务3)时,我必须传递slno,order,来自Web服务2的标记以及用户在动态创建的字段中输入的“答案” '回答'键。我如何获得这4个参数[slno,order,flag(来自web服务2)和回答(来自动态文本字段)]以发布到Web服务3?

- (void) fetchStrings:(NSArray *)textArray
{
    NSLog(@"Array string = %@", textArray); //I get the array that the user enters in the dynamically created text field here

    NSOperationQueue *queue = [[NSOperationQueue alloc] init];

    NSUserDefaults *getDefaults = [NSUserDefaults standardUserDefaults];
    NSString *uidObject = [getDefaults objectForKey:@"UIDKEY"];


    NSString *str = [NSString stringWithFormat:@"{\"ProjID\": \"%@\",\"Uid\": \"%@\",\"EmailID\": \"%@\",", projectIdGobal, uidObject, emailFromLogin];
    str = [str stringByAppendingString:@"\"ProjectInviterFQAnswers\": ["];

    **for (SaveAsking *saveAsk in textArray) {
        str = [str stringByAppendingString:[NSString stringWithFormat:@"{\"slno\":\"%@\",\"Answer\": \"%@\",\"order\": \"%@\", \"flag\": \"%@\"},", saveAsk.slno, saveAsk.answer, saveAsk.order, saveAsk.flag]]; // I want to save the parameters here
    }**

// SaveAsking is a nsobject class where I have used a self created delegate for slno answer order and flag
    str = [str stringByAppendingString:@"]}"];
    NSLog(@"String is === %@", str);


    NSURL *url = [NSURL URLWithString:@"some url"];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];

    NSData *requestData = [str dataUsingEncoding:NSUTF8StringEncoding];

    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody: requestData];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [connection start];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
        if(error || !data)
        {
            NSLog(@"JSON Data not posted!");
            [activity stopAnimating];
            UIAlertView *alertMessage = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Data not saved" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alertMessage show];
        }
        else
        {
            [activity startAnimating];
            NSLog(@"JSON data posted! :)");
            NSError *error = Nil;
            NSJSONSerialization *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
            NSLog(@"Response is %@", jsonObject);
        }
    }];

}

如果你明白我想要实现的目标,请纠正我的流程。左框中的迭代次数==右框中的迭代次数,结果位于需要发布到Web服务的中间框中。

enter image description here

1 个答案:

答案 0 :(得分:1)

尝试保留请求的字典,其中密钥是动态创建的UITextField,值将是另一个字典,其中包含您需要发送的值。

因此,当您创建textField时,在将其添加到子视图后,使用您的值(sino,order,flag)创建一个字典,并将该字典设置为文本字段。

当您准备好发送数据时,您将在textField和webservice3的值之间建立直接连接。