NSString в NSArray - PullRequest
       23

NSString в NSArray

4 голосов
/ 09 июня 2011

В настоящее время я получаю файл и сохраняю его в NSString.Затем я создаю массив из строки и представляю его в виде таблицы.Это работает в определенной степени.В настоящее время я получаю такие данные:

CompanyName | AccountCode \ r \ nCompanyName | AccountCode \ r \ nCompanyName | AccountCode \ r \ n и т. Д.

в данный момент яделать:

NSString *dataString = [NSString stringWithContentsOfURL:url encoding:nil error:nil];
myArray = [dataString componentsSeparatedByString:@"\r\n"];

, который отображает данные в виде:

CompanyName | AccountCode CompanyName | AccountCode CompanyName | AccountCode

Мой вопрос: Могу ли я разделить «dataString» на2-х мерный массив?или я должен создать 2 массива (один с CompanyName, другой с AccountCode).И как мне это сделать?

Спасибо

РЕДАКТИРОВАТЬ:

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";  

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell.
    if (testArray.count >indexPath.row) {

        cell.textLabel.text = [testArray2 objectAtIndex:0];
        cell.detailTextLabel.text = [testArray2 objectAtIndex:1];

    }

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    return cell;
}

РЕДАКТИРОВАТЬ:

для целей тестирования мой код:

- (void)viewDidLoad {
    [super viewDidLoad];

    testArray = [[NSArray alloc] init];
    NSString *testString = @"Sam|26,Hannah|22,Adam|30,Carlie|32";
    testArray = [testString componentsSeparatedByString:@","];

    dict = [NSMutableDictionary dictionary];
    for (NSString *s in testArray) {

        testArray2 = [s componentsSeparatedByString:@"|"];
        [dict setObject:[testArray2 objectAtIndex:1] forKey:[testArray2 objectAtIndex:0]];
    }

    NSLog(@"Dictionary: %@", [dict description]);
    NSLog(@"Account code for CompanyName1: %@", [dict objectForKey:@"CompanyName1"]);
}

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

    static NSString *CellIdentifier = @"Cell";  

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell.
    if (testArray.count >indexPath.row) {

        cell.textLabel.text = [testArray2 objectAtIndex:0];
        cell.detailTextLabel.text = [testArray2 objectAtIndex:1];

    }

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    return cell;
}

Ответы [ 2 ]

6 голосов
/ 09 июня 2011

Marzapower верен, вы, вероятно, захотите использовать NSDictionary или NSMutableDictionary для хранения пар ключ-значение.Прямо под кодом, приведенным выше, вы можете использовать этот код:

NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (NSString *s in myArray)
{
    NSArray *arr = [s componentsSeparatedByString:@"|"];
    [dict setObject:[arr objectAtIndex:1] forKey:[arr objectAtIndex:0]];
}
NSLog(@"Dictionary: %@", [dict description]);
NSLog(@"Account code for CompanyName1: %@", [dict objectForKey:@"CompanyName1"]);

Код регистрации показывает результирующий словарь, а также способ извлечения объекта на основе названия компании.Помните, что здесь нет проверки ошибок, если в одном из компонентов массива нет символа канала, строка setObject взорвется.

И, конечно, если вы хотите, чтобы в качестве ключа использовался код учетной записи,просто переверните 1 и 0 в строке setObject.

РЕДАКТИРОВАТЬ: в cellForRowAtIndexPath вы должны получить доступ к словарю dict вместо массива testArray2.Например, вы, вероятно, захотите сделать что-то вроде этого:

cell.textLabel.text = [[dict allKeys] objectAtIndex:[indexPath row]];
cell.detailTextLabel.text = [dict objectForKey:cell.textLabel.text];

(Надеюсь, это правильно, у меня нет способа немедленно протестировать это в Xcode.)

1 голос
/ 09 июня 2011

Вы можете создать ассоциативный массив, также называемый «словарь». Со словарем вы можете связать строку (значение) с другой (ключ). Таким образом, вы получите что-то вроде этого:

"Company1" => "account code 1",
"Company2" => "account code 2",
...

Затем вы можете перебирать его ключи с помощью метода allKeys. Пожалуйста, обратитесь к документации NSMutableDictionary для получения дополнительной информации.

...