Приветствую, люди.
В первый раз я погружаюсь в Objective-C. Это пинает мою задницу C #, но (хе) я думаю, что наконец-то начинаю «понимать» некоторые концепции.
Я пишу приложение для iPhone, которое подключается к веб-службе, извлекает данные в формате XML, анализирует данные и отображает их как UITableView. Щелчок по ячейке в табличном представлении загружает подробное представление и т. Д.
Я сталкиваюсь с некоторыми концептуальными проблемами. В C # большинство элементов управления имеют отображаемую метку и значение. Что облегчает прикрепление событий (еще одна вещь, к которой я пристрастился) к ячейке или записи и отключение значения для дальнейшего поиска.
Проблема, с которой я столкнулся, заключается в том, что UITableView, хотя и создан для подробного вида, похоже, не имеет свойства значения или чего-либо, что я мог бы интеллектуально отключить, чтобы передать идентификатор в подробный вид и заполнить его.
В настоящее время я занимаюсь этим, анализируя мой XML-фид в NSMutableArray, который содержит все данные о конкретной записи. Я заполняю UITableView на основе одного конкретного поля в этом массиве. А затем я использую objectAtIndex: indexPath.row для передачи любых идентификаторов или тому подобного в подробный вид.
Я мог бы действовать так и заставить его работать, но все это похоже на большой беспорядок и похоже, что он будет монстром, который будет поддерживать / уменьшать масштаб. Итак, с этим, как говорится ... пожалуйста, помогите мне! Я собираюсь опубликовать большую часть своего кода, чтобы вы могли видеть, насколько плохо я подхожу к этому:)
Контроллер Table View, который я ужасно перегружаю:
#import "InvoicesTableViewController.h"
#import "Wrapper.h"
#import "InvoiceDetailViewController.h"
@implementation InvoicesTableViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)dealloc
{
[listOfItems release];
[restAPI release];
[parameters release];
[super dealloc];
}
- (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 - Wrapper
- (void)wrapper:(Wrapper *)wrapper didRetrieveData:(NSData *)data
{
NSData *result = [[restAPI responseAsText] dataUsingEncoding:NSUTF8StringEncoding];
if (result != nil)
{
NSXMLParser *parser = [[[NSXMLParser alloc] initWithData:result] autorelease];
parser.delegate = self;
[parser parse];
}
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
#pragma mark - Parser
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
if(OneInvoice == nil)
{
OneInvoice = [[NSMutableArray alloc] init];
}
if ([elementName isEqualToString:@"invoice"])
{
[OneInvoice addObject:[attributeDict valueForKey:@"uri"]];
[OneInvoice addObject:[attributeDict valueForKey:@"total"]];
[OneInvoice addObject:[attributeDict valueForKey:@"total_due"]];
[OneInvoice addObject:[attributeDict valueForKey:@"status"]];
}
if ([elementName isEqualToString:@"client"])
{
[OneInvoice addObject:[attributeDict valueForKey:@"name"]];
[listOfItems addObject:[[NSMutableArray alloc] initWithArray:OneInvoice copyItems:YES]];
[OneInvoice release];
OneInvoice = nil;
[self.tableView reloadData];
}
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
listOfItems = [[NSMutableArray alloc] init];
//Set the title
self.navigationItem.title = @"Invoices";
if(restAPI == nil) {
restAPI = [[Wrapper alloc] init];
}
restAPI.delegate = self;
parameters = nil;
restAPI.mimeType = @"application/vnd.site+xml";
url = [NSURL URLWithString: @"https://user:pass@site.com/invoices/?status=all"];
[restAPI sendRequestTo:url usingVerb: @"GET" withParameters: parameters];
// 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
{
[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 (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [listOfItems 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];
}
// Setup the cell
NSString *cellValue = [NSString stringWithFormat:@"%@ - %@", [[listOfItems objectAtIndex:indexPath.row] objectAtIndex:4],[[listOfItems objectAtIndex:indexPath.row] objectAtIndex:1]];
cell.textLabel.text = cellValue;
return cell;
}
- (UITableViewCellAccessoryType)tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
//return UITableViewCellAccessoryDetailDisclosureButton;
return UITableViewCellAccessoryDetailDisclosureButton;
//return UITableViewCellAccessoryDisclosureIndicator;
}
/*
// 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;
}
*/
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *invoiceURL = [[listOfItems objectAtIndex:indexPath.row] objectAtIndex:0];
InvoiceDetailViewController *dvController = [[InvoiceDetailViewController alloc] initWithNibName:@"InvoiceDetailViewController" bundle:[NSBundle mainBundle]];
dvController.invoiceURL = invoiceURL;
[self.navigationController pushViewController:dvController animated:YES];
[dvController release];
dvController = nil;
}
@end
Пожалуйста, не стесняйтесь издеваться над моей формой. Я очень неопытен в C / C ++, и особенно в Objective-C. Прошлой ночью я сковывал это вместе, чтобы заставить что-то работать, на что я могу опираться.
Спасибо миллион,
Клифтон