Как заполнить UITableView ответом JSON от другого ViewController? - PullRequest
0 голосов
/ 23 января 2012

Я гуглил и искал в stackoverflow.com, но не смог избавиться от этой ситуации, как я могу заполнить TableView ответом GET.Я отправляю GET и анализирую ответ в методе DetailViewController (мой главный контроллер) и хочу инициализировать TableViewCell с частью ответа, а детали этой ячейки с другой частью. Я создал messageTableView и messageDetailViewController.. Я тоже могу поделиться кодом, если вопрос недостаточно ясен.Спасибо

РЕДАКТИРОВАТЬ Я знаю, что это нежелательно, но я поделился всеми кодами, так как не могу связать переменные между viewControllers, я могу перемещаться между представлениями, но я не могу делиться переменнымимежду собой ..

Вот файл интерфейса моего DetailViewController (в моем приложении это основной View Controller)

#import <UIKit/UIKit.h>

@interface BNT_1DetailViewController : UIViewController <UISplitViewControllerDelegate>
{
    NSMutableArray *buttons;
    NSString *userName, *password, *serverIP;
    NSDictionary *mess;
    IBOutlet UITextField *userNameF;
    IBOutlet UITextField *passwordF;
    IBOutlet UITextField *serverF;
    NSURL *url;
    NSMutableArray *mesag;
    IBOutlet UIButton *acceptButton;
    NSMutableArray *mesID; //saving meesage ID s to NSMutableArray
    NSMutableArray *content; 

}
@property(retain,nonatomic)NSMutableArray *mesID,*content;
@property(assign,nonatomic)NSMutableArray *mesag ;
@property(retain, nonatomic)NSDictionary *mess;
//@property (retain,nonatomic)  NSMutableArray *buttons;
@property (retain, nonatomic) UITextField *userNameF;
@property (retain, nonatomic) UITextField *passwordF;
@property (retain, nonatomic) UITextField *serverF;
@property (retain, nonatomic) UIButton *acceptButton;
@property (retain, nonatomic) NSString *userName, *password, *serverIP;
@property (strong, nonatomic) id detailItem;
@property(retain,nonatomic)NSURL *url;
@property (strong, nonatomic) IBOutlet UILabel *detailDescriptionLabel;

-(IBAction)acceptAct:(id)sender;
-(IBAction)readMessages:(id)sender;
-(IBAction)secondAct:(id)sender;
@end

И вот файл его реализации:

#import "BNT_1DetailViewController.h"
#import "mainMenu.h"
#import "messages.h"
@interface BNT_1DetailViewController ()
@property (strong, nonatomic) UIPopoverController *masterPopoverController;
- (void)configureView;
@end

@implementation BNT_1DetailViewController
@synthesize content,mesID,url;
@synthesize mesag,mess;
@synthesize userNameF, passwordF, serverF, acceptButton;
@synthesize userName, password, serverIP;
@synthesize detailItem = _detailItem;
@synthesize detailDescriptionLabel = _detailDescriptionLabel;
@synthesize masterPopoverController = _masterPopoverController;

-(IBAction)readMessages:(id)sender{

    messages *message=[[messages alloc]initWithNibName:@"messages" bundle:nil];
    /*
     message.mesid=mesID;
     message.contents=content;
     */
    [self.navigationController pushViewController:message animated:TRUE];




}
-(IBAction)acceptAct:(id)sender{


    userName=[[NSString alloc] initWithString:userNameF.text ];
    [userNameF setText:userName];
    NSUserDefaults *userNameDef= [NSUserDefaults standardUserDefaults];
    [userNameDef setObject:userName forKey:@"userNameKey"];
    password =[[NSString alloc] initWithString:passwordF.text];
    [passwordF setText:password];
    NSUserDefaults *passDef=[NSUserDefaults standardUserDefaults];
    [passDef setObject:password forKey:@"passwordKey"];
    serverIP=[[NSString alloc] initWithString: serverF.text];
    [serverF setText:serverIP];
    NSUserDefaults *serverDef=[NSUserDefaults standardUserDefaults];
    [serverDef setObject:serverIP forKey:@"serverIPKey"];
    [userNameDef synchronize];
    [serverDef synchronize];
    [passDef synchronize];


    UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"BNTPRO "
                                                      message:@"Your User Informations are going to be sent to server. Do you accept?"
                                                     delegate:self
                                            cancelButtonTitle:@"OK"
                                            otherButtonTitles:@"Cancel",  nil];
    [message show];

}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString *title = [alertView buttonTitleAtIndex:buttonIndex];

    if([title isEqualToString:@"OK"])
    {
        if([userNameF.text isEqualToString:@""]|| [passwordF.text isEqualToString:@""] || [serverF.text length]<6) 
        {
            UIAlertView *message1 = [[UIAlertView alloc] initWithTitle:@"BNTPRO "
                                                               message:@"Your User Informations are not defined properly!"
                                                              delegate:nil
                                                     cancelButtonTitle:@"OK"
                                                     otherButtonTitles:  nil];

            [message1 show];
            [userNameF  resignFirstResponder];
            [passwordF resignFirstResponder];
            return;
        }
        mainMenu *ma=[[mainMenu alloc]initWithNibName:@"mainMenu" bundle:nil];
        NSString *str1=[@"?username=" stringByAppendingString:userNameF.text];
        NSString *str2=[@"&password=" stringByAppendingString:passwordF.text];
        NSString *str3=[str1 stringByAppendingString:str2];
        NSString *str4 =[@"http://" stringByAppendingString:serverF.text];


       url=[NSURL URLWithString:[str4 stringByAppendingString:[@"/ipad/login.php" stringByAppendingString:str3]]];
        //get the url to jsondata
        NSData *jSonData=[NSData dataWithContentsOfURL:url];

        if (jSonData!=nil) {
            NSError *error=nil;
            id result=[NSJSONSerialization JSONObjectWithData:jSonData options:
                       NSJSONReadingMutableContainers error:&error];
            NSLog(@"%@",result);       

            if (error==nil) {
            mess=[result objectForKey:@"message"];
                NSDictionary *messContent=[mess valueForKeyPath:@"message"];
                NSDictionary *messID=[mess valueForKeyPath:@"ID"];
                NSString*key1=[ result objectForKey:@"key" ];                
                NSString *s1=[@"http://" stringByAppendingString:serverF.text];
                NSString *s2=[s1 stringByAppendingString:@"/ipad/button.php"];
                NSURL *url2=[NSURL URLWithString:[s2 stringByAppendingString:[@"?key=" stringByAppendingString:key1]]];

                NSData *data2=[NSData dataWithContentsOfURL:url2];
                id result2=[NSJSONSerialization JSONObjectWithData:data2 options:NSJSONReadingMutableContainers error:nil];

                mesID = [NSMutableArray array];//saving meesage ID s to NSMutableArray
                content = [NSMutableArray array];    
                for ( mesag in mess) {

                    //i want to populate TableViewCells with the messID and the details of each cell(push in new view controller) will contain 'content' above

                  /*
                     [mesID addObject:[mesag objectForKey:@"ID"]];
                     [content addObject:[mesag objectForKey:@"message"]];    
                     */    
                    [[NSUserDefaults standardUserDefaults] setObject:messID forKey:@"message"];
                    [[NSUserDefaults standardUserDefaults] setObject:messContent forKey:@"messContent"];

                    // NSLog(@"%@", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
                    //   NSLog(@"The Message with ID %@ is: %@\n",messID,messContent);

                }

                NSLog(@"MessID: %@",mesID);
                NSLog(@"Context: %@",content);


                buttons = [NSMutableArray array];
                CGFloat yPosition = 60.0f;
                CGFloat xPosition = 40.0f;

                const CGFloat buttonHeight = 75.0f;
                const CGFloat buttonMargin = 50.0f;
                UIButton *bt=[UIButton buttonWithType:UIButtonTypeRoundedRect];

                [bt setTitle:@"Messages" forState:UIControlStateNormal];
                [bt addTarget:self action:@selector(readMessages:) forControlEvents:UIControlEventTouchUpInside];
                bt.titleLabel.font=[UIFont systemFontOfSize:25];
                bt.frame=CGRectMake(300.0f, 700.0f,180.0f , 70.0f);
                [ma.view addSubview:bt];

                for(NSDictionary* buttonData in result2) { 
                    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
                    NSString* buttonTitle = [buttonData objectForKey:@"name"];
                    NSString* buttonID=[buttonData objectForKey:@"ID"];
                    [button setTitle:buttonTitle forState:UIControlStateNormal];
                    [button setTag:[buttonID intValue]];
                    button.titleLabel.font=[UIFont systemFontOfSize:28];
                    button.frame = CGRectMake(xPosition, yPosition, 210.0f, buttonHeight);
                    [button addTarget:self action:@selector(secondAct:) forControlEvents:UIControlEventTouchUpInside];
                    [ma.view addSubview:button];
                    //   [v.buttons addObject:button];

                    xPosition = 260.0f;
                    yPosition+= buttonHeight + buttonMargin;

                }


            [self.navigationController pushViewController:ma animated:TRUE];


}
        }} }


-(IBAction)secondAct:(id)sender{

    NSLog(@"ABC: %d",[sender tag]);

}

- (void)dealloc
{
    [_detailItem release];
    [_detailDescriptionLabel release];
    [_masterPopoverController release];
    [super dealloc];
}

#pragma mark - Managing the detail item

- (void)setDetailItem:(id)newDetailItem
{
    if (_detailItem != newDetailItem) {
        [_detailItem release]; 
        _detailItem = [newDetailItem retain]; 

        // Update the view.
        [self configureView];
    }

    if (self.masterPopoverController != nil) {
        [self.masterPopoverController dismissPopoverAnimated:YES];
    }        
}

- (void)configureView
{
    // Update the user interface for the detail item.

    if (self.detailItem) {
        self.detailDescriptionLabel.text = [self.detailItem description];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    [passwordF setSecureTextEntry:YES];
    userNameF.font=[UIFont systemFontOfSize:24];

    userNameF.frame = CGRectMake(320.0f,60.0f,360.0f,50.0f);
    passwordF.frame = CGRectMake(320.0f,145.0f,360.0f,50.0f);
    serverF.frame= CGRectMake(320.0f,235.0f,360.0f,50.0f);
    userNameF.font=[UIFont boldSystemFontOfSize:24];
    [userNameF becomeFirstResponder];
    serverF.font=[UIFont boldSystemFontOfSize:24];
    passwordF.font=[UIFont systemFontOfSize:24];


    acceptButton.titleLabel.font=[UIFont boldSystemFontOfSize:26];
    // Do any additional setup after loading the view, typically from a nib.
    [self configureView];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return YES;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = NSLocalizedString(@"Detail", @"Detail");
    }
    return self;
}

#pragma mark - Split view

- (void)splitViewController:(UISplitViewController *)splitController willHideViewController:(UIViewController *)viewController withBarButtonItem:(UIBarButtonItem *)barButtonItem forPopoverController:(UIPopoverController *)popoverController
{
    barButtonItem.title = NSLocalizedString(@"Master", @"Master");
    [self.navigationItem setLeftBarButtonItem:barButtonItem animated:YES];
    self.masterPopoverController = popoverController;
}

- (void)splitViewController:(UISplitViewController *)splitController willShowViewController:(UIViewController *)viewController invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem
{
    // Called when the view is shown again in the split view, invalidating the button and popover controller.
    [self.navigationItem setLeftBarButtonItem:nil animated:YES];
    self.masterPopoverController = nil;
}

@end

я хочу заполнить TableViewCells messID, и детали каждой ячейки (push в новом контроллере представления) будут содержать «content» выше

Это мой TableViewController файлвызываемые сообщения: (.h файл)

#import <UIKit/UIKit.h>

@interface messages : UITableViewController{

    NSMutableArray *mesid,*contents; 

}

@property(retain,nonatomic)NSMutableArray *mesid,*contents;


@end

и .m файл:

#import "messages.h"
#import "messageDetail.h"
@implementation messages
@synthesize mesid;
- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
     self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
     self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    }

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return YES;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#warning Incomplete method implementation.
    // Return the number of rows in the section.

   return [mesid count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    cell.textLabel.text=[mesid objectAtIndex:indexPath.row];
    [tableView reloadData]; 
    // Configure the cell...

    return cell;
}


// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}



// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.

     messageDetail *detailViewController = [[messageDetail alloc] initWithNibName:@"messageDetail" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     detailViewController.title=@"Message Detail";
     [detailViewController release];

}

@end

Мой последний контроллер - messageDetails.Его интерфейсный файл:

#import <UIKit/UIKit.h>

@interface messageDetail : UIViewController

@end

И последний, файл реализации messageDetail:

#import "messageDetail.h"

@implementation messageDetail

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return YES;
}

@end

1 Ответ

2 голосов
/ 23 января 2012

У вас есть несколько проблем, которые я обнаружил, просто взглянув: 1. У вас есть экземпляр UITableViewController.Правильная инициализация для UITableViewController initWithStyle: Используйте это вместо этого.В противном случае вам нужно проделать дополнительную работу, и она действительно не нужна.2. Вы проверяете строки с помощью кнопок в вашем экземпляре UIAlertView.Моя рекомендация не делать этого.Строки как-то изменчивы.Многоязычность может быть вставлена ​​как функция, и после этого у вас могут возникнуть проблемы.Вместо этого проверьте индекс.Это простое целое, а не предупреждение о головной боли!3. Вы установили NSMutableArray как свойство в своем классе messages.Почему бы вам не заполнить это.Вот почему информация не появляется в вашей таблице: потому что вы не предоставляете ее конкретному классу.От контроллера вы инициализируете контроллер (класс, который содержит табличное представление), предоставьте его содержимое из исходного контроллера.

Советы: 4. Для стандартизации назовите ваши классы заглавными буквами, а переменные - маленькими.,Константы должны начинаться с буквы "k".

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...