Разбор CSV и обновление подробных сведений в iOS - PullRequest
0 голосов
/ 11 августа 2011

Моя конфигурация: Панель вкладок с tableView -> щелкните по строке -> detailview

Моя проблема: я делаю запрос с asihttp. Все идет нормально. Я получаю ответ как:

name;tel;email
Hans Mustermann;0123/45678;info@yourdomain.com
Harry the second;98765/12345;my@email.com

На данный момент я обрабатываю ответ как:

NSArray *cusNameDataArray = nil;
cusNameDataArray = [[response componentsSeparatedByString:@"\n"]retain];
self.cusNameDataArray =[[NSMutableArray alloc] initWithArray:cusNameDataArray];
[cusNameDataArray release];

и в:

-(UITableViewCell *)tableView:(UITableView *)cusTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifier = @"Cell";
    UITableViewCell *cell = [self.cusTableView dequeueReusableCellWithIdentifier:identifier];
    if(cell == nil) 
   //cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:identifier] autorelease];
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier] autorelease];


// Set up the cell...
    cell.textLabel.font = [UIFont fontWithName:@"Verdana" size:12];
cell.textLabel.text = **here i want the name**;
cell.detailTextLabel.font = [UIFont fontWithName:@"Verdana" size:10];
cell.detailTextLabel.text = *here i want the email and tel;

return cell;
}

Вы видите, что я просто хочу имя в cell.textLabel.text и в cell.detailTextLabel.text электронная почта и телефон

Может ли кто-нибудь помочь мне привести пример? Я потратил столько времени на это решение, но ничего не нашел


спасибо за ваш парсер. Я сделал это сейчас таким образом, но без шансов.

ячейки tableview пусты -> cell.textlabel.text и cell.detailtextlabel.text

я совершил глупую ошибку?

- (void)viewDidLoad
{
[super viewDidLoad];

self.title = NSLocalizedString(@"Customers", @"My Customers");

NSURL *url = [NSURL URLWithString:@"http://www.yourdomain.com/some.php?do=yes"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
    NSString *response = [request responseString];
    NSLog(@"%@", response);

    NSArray *cusDataArray = nil;
    cusDataArray = [[response componentsSeparatedByString:@"\n"]retain];

    // Allocate my customer array
    self.cusDataArray =[[NSMutableArray alloc] init];

for (int i=0; i<[cusTempArray count]; i++)
{
    NSString *cusLine = [cusTempArray objectAtIndex:i];
    NSArray *cusComponents = [cusLine componentsSeparatedByString:@";"];

    // cusComponents now contains 3 entries - name, number, e-mail. Add this to your customer data array
    [self.cusDataArray addObject:cusComponents];
}

}

[cusDataArray release];
}

 -(UITableViewCell *)tableView:(UITableView *)cusTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *identifier = @"Cell";

UITableViewCell *cell = [self.cusTableView dequeueReusableCellWithIdentifier:identifier];
if(cell == nil) 
   //cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:identifier] autorelease];
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier] autorelease];

    // Iterate over ever line and break it up into its components
for (int i=0; i<[cusTempArray count]; i++)
{
    NSString *cusLine = [cusTempArray objectAtIndex:i];
    NSArray *cusComponents = [cusLine componentsSeparatedByString:@";"];

    // cusComponents now contains 3 entries - name, number, e-mail. Add this to your customer data array
    [self.cusDataArray addObject:cusComponents];
}

//Set up the cell...
cell.textLabel.font = [UIFont fontWithName:@"Verdana" size:12];
NSArray *customerData = [self.cusDataArray objectAtIndex:0];
NSString *customerName = [customerData objectAtIndex:0];
NSString *customerPhone = [customerData objectAtIndex:1];
cell.textLabel.text = customerName;
cell.detailTextLabel.font = [UIFont fontWithName:@"Verdana" size:10];
cell.detailTextLabel.text = [self.cusDataArray objectAtIndex:1];

return cell;
}

1 Ответ

0 голосов
/ 11 августа 2011

Я написал библиотеку CSV, которая может справиться с этим, даже если ваши данные не csv:

https://github.com/davedelong/CHCSVParser

В вашем случае, так как вам нужно указать пользовательский разделитель,вы бы сделали что-то вроде этого:

NSString *data = @"name;tel;email\nHans Mustermann;0123/45678;info@yourdomain.com\nHarry the second;98765/12345;my@email.com";
NSError *error = nil;
NSArray *split = [[NSArray alloc] initWithContentsOfCSVString:data encoding:NSUTF8StringEncoding delimiter:@";" error:&error];
NSLog(@"%@", split);
[split release];

Когда я запускаю это, он записывает:

(
        (
        name,
        tel,
        email
    ),
        (
        "Hans Mustermann",
        "0123/45678",
        "info@yourdomain.com"
    ),
        (
        "Harry the second",
        "98765/12345",
        "my@email.com"
    )
)
...