как код для Tableview загружает элементы NSMutableArray? - PullRequest
0 голосов
/ 29 февраля 2012

Привет всем в соответствии с приведенным ниже кодом. Я пытаюсь загрузить элементы NSMutableArray в таблицу, но при этом возникает проблема вроде

ContactTesting [1040: f803] * Завершение работы приложения из-занеперехваченное исключение «NSInvalidArgumentException», причина: ' - [NSMutableArray count]: метод отправлен в неинициализированный объект изменяемого массива' ** Стек первого вызова вызова: (0x13bc052 0x154dd0a 0x13a820b 0x247b 0x1edf2cax0x07x0x0807 0x1 087 0x07 807 0x1 0 0 07 07 0 0 07 070xa7783 0x52322 0x13bde72 0x1d6692d 0x1d70827 0x1cf6fa7 0x1cf8ea6 0x1d8430c 0x124c6 0x12bd6 0x21743 0x221f8 0x15aa9 0x12a6fa9 0x13901c5 0x12f5022 0x12f390a 0x12f2db4 0x12f2ccb 0x122a7 0x13a9b 0x1bc8 0x1b25 0x1)

в основном я получаю NSMutableArray *array предметы, как например,

1014 *

но когда я использую методы tableView, он выходит из функциональности, поэтому, как решить проблему, дать решение, это слишком актуально для меня в iphone

- (void)viewDidLoad
{
   [super viewDidLoad];


    [self testing];

    array=[NSMutableArray alloc];
    myTableView.delegate=self;
    myTableView.dataSource=self;
    myTableView.separatorStyle=  UITableViewCellSeparatorStyleNone;

    myTableView.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"list.png"]];
    myTableView.scrollEnabled=YES;


// Do any additional setup after loading the view, typically from a nib.
}







- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    return 1;   
}
- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {
    return [array count];
}

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

static NSString *CellIdentifier = @"Cell";
//here you check for PreCreated cell.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}

//Fill the cells...  
cell.textLabel.text = [array objectAtIndex: indexPath.row];
//yourMutableArray is Array 
return cell;
}

-(void)testing{
//  NSLog(@">>>>>>>>>>>>233333");

NSString *jobSearchUrlString = [NSString stringWithFormat:@"http://infra2appsmobile.cloudapp.net/Infra2Apps.svc/Contacts"];
//NSLog(@"url for new articles is = %@",jobSearchUrlString);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:jobSearchUrlString]];   

NSURLConnection *theconnection =  [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theconnection) {
    RoutData = [[NSMutableData alloc] init];
}




}



-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{   

[RoutData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[RoutData appendData:data];

NSString *thexml = [[NSString alloc] initWithData:RoutData encoding:NSUTF8StringEncoding];

NSDictionary *dictXML= [XMLReader dictionaryForXMLString:thexml error:nil];

NSMutableArray *arrStation = [[dictXML objectForKey:@"feed"] objectForKey:@"entry"] ;//this would return the array of station dictionaries



//    for (int i=0; i<[arrStation count]; i++) {
//        NSLog(@"--->>>ContactNameis:<<<---- %@",[[[[[arrStation objectAtIndex:i] objectForKey:@"content"] objectForKey:@"m:properties"] objectForKey:@"d:ContactName"] objectForKey:@"text"]);



    array=[[NSMutableArray alloc]init];
    for (int i=0; i<[arrStation count]; i++){
        NSString *str=[[[[[arrStation objectAtIndex:i] objectForKey:@"content"]   objectForKey:@"m:properties"] objectForKey:@"d:ContactName"] objectForKey:@"text"];
      //  NSlog(@"name is : %@",str);
        //NSLog(@"name is->>>>>>> : %@",str);
        [array addObject:str];
        NSLog(@"name is->>>>>>> : %@",array);

               }



    // NSString *str=[[arrStation objectAtIndex:i ] objectForKey:@"d:ContactName"];
    //NSLog(@"8********************8%@",[[arrStation objectAtIndex:i ] objectForKey:@"d:ContactName"]);
    //NSLog(@"--->>>id is ::<<<---- %@",[[[[[arrStation objectAtIndex:i] objectForKey:@"content"] objectForKey:@"m:properties"] objectForKey:@"d:Id"] objectForKey:@"text"]);
    //        
    // NSLog(@"--->>>Emails ::<<<---- %@",[[[[[arrStation objectAtIndex:i] objectForKey:@"content"] objectForKey:@"m:properties"] objectForKey:@"d:Email"] objectForKey:@"text"]);
//        
//NSLog(@"--------->>>>>>>>>>><<<<<<<<<<<%@",arrStation);

 }
}

Ответы [ 3 ]

1 голос
/ 29 февраля 2012

Вам не хватает init в первоначально выделенном методе array в viewDidLoad, потому что вскоре после этого tableView запросит количество элементов в разделе 0, безусловно, до того, как элементы будут загружены изсеть.И он попытается работать с неинициализированным NSMutableArray, в точности так, как говорит исключение.

После того, как вы загрузите материал и закончите анализ, заполнив массив, перезагрузите раздел или всю таблицу.

1 голос
/ 29 февраля 2012

Сделайте это в вашем viewDidLoad методе

array = [[NSMutableArray alloc] init];
1 голос
/ 29 февраля 2012

После получения всех данных перезагрузите tableView

// array=[[NSMutableArray alloc]init];   remove this 
for (int i=0; i<[arrStation count]; i++){
     NSString *str=[[[[[arrStation objectAtIndex:i] objectForKey:@"content"]   objectForKey:@"m:properties"] objectForKey:@"d:ContactName"] objectForKey:@"text"];
     // NSlog(@"name is : %@",str);
     // NSLog(@"name is->>>>>>> : %@",str);
     [array addObject:str];
     NSLog(@"name is->>>>>>> : %@",array);
     [myTableView reloadData];
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...