user3859201
user3859201

Reputation: 11

My app is crashing when updating my table view

I am doing a database based application. My app needs to update a database table and simultaneously it needs to update the table view i.e. generated based on that particular database table.

Here's is the code i have written

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.courses.count;
}

-(void)viewWillAppear:(BOOL)animated {

    self.usernameLBL.text = [NSString stringWithFormat:@"Welcome, %@", self.del.username];

    [self loadCourses];

//    NSLog(@"The courses count is %d", self.courses.count);

}

-(void)loadCourses {

    NSString * stringUrl = [NSString stringWithFormat:"Some URL";

    NSURL * uRL = [NSURL URLWithString:[stringUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

    NSURLRequest * request = [NSURLRequest requestWithURL:uRL];

    NSError * error;

    NSData * results = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];

    self.courses = [NSJSONSerialization JSONObjectWithData:results options:0 error:&error];

    NSLog(@"The courses array count is %d", self.courses.count);

    [self.tableView reloadData];
}


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

    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

    NSDictionary * dict = self.courses[indexPath.row];

    cell.textLabel.text = dict[@"name"];

    cell.detailTextLabel.text = dict[@"id"];

    return cell;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.courses = [[NSMutableArray alloc] init];

    self.del = [[UIApplication sharedApplication] delegate];

    NSString * strURL = [NSString stringWithFormat:"Some URL";

//    NSLog(@"The username is %@", self.del.username);

    NSURL * url = [NSURL URLWithString:[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

    NSURLRequest * request = [NSURLRequest requestWithURL:url];

    NSError * error;

    NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];

    //    NSLog(@"The data is %@", data);

    NSDictionary * result = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];

    //    NSLog(@"The error is %@", error);

//    NSLog(@"The value returned is %@", result[@"image"]);

    if(![result[@"image"] isEqualToString:@"empty"]){

        NSString * urlLocation = result[@"image"];

        self.adminIMG.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[urlLocation stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]]]];
    }

    // Do any additional setup after loading the view.
}

- (IBAction)addNewCourse:(id)sender {

    NSString * strURL = [NSString stringWithFormat:"Some URL";

    NSURL * url = [NSURL URLWithString:[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

    NSURLRequest * request = [NSURLRequest requestWithURL:url];

    NSError * error;

    NSData * results = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];

    NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:results options:0 error:&error];

    if([dict[@"response"] isEqualToString:@"success"]) {

        NSLog(@"New course added");

        UIAlertView * success = [[UIAlertView alloc] initWithTitle:@"New course added successfully" message:@"You successfully added a new course" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];

        [success show];

    }else {

        NSLog(@"Course not added");
    }

    [self.courses removeAllObjects];

    [self viewDidLoad];

    [self viewWillAppear:YES];
}

And i got this error.

Error: Evaluation[13335:60b] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray objectForKeyedSubscript:]: unrecognized selector sent to instance 0xb7d26d0'

I tried many solutions available on the internet but those are not working for me. Anyone can help me, please. Thanks in advance :)

Upvotes: 1

Views: 114

Answers (3)

Jasmin
Jasmin

Reputation: 794

I think your problem is here.. your targeting AppDelegate as self.delegate

self.del = [[UIApplication sharedApplication] delegate];

And AppDelegate runs onetime at start of application only that's why your are getting error

Upvotes: 0

meda
meda

Reputation: 45490

your issue might be here

[self.courses removeAllObjects];
[self viewDidLoad];
[self viewWillAppear:YES];

you don't have to clear your array, try this:

function:

- (void)addCourse{

    NSString * strURL = [NSString stringWithFormat:"Some URL";    
    NSURL * url = [NSURL URLWithString:
       [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];    
    NSURLRequest * request = [NSURLRequest requestWithURL:url];    
    NSError * error; 
    NSData * results = [NSURLConnection sendSynchronousRequest:request
                                             returningResponse:nil error:&error];
    NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:results 
                                                          options:0 error:&error];

    if([dict[@"response"] isEqualToString:@"success"]) {    
        NSLog(@"New course added");    
        UIAlertView * success = [[UIAlertView alloc] 
                                 initWithTitle:@"New course added successfully" 
                                  message:@"You successfully added a new course" 
                                      delegate:nil
                             cancelButtonTitle:@"OK" 
                             otherButtonTitles: nil];    
        [success show];    
    }else {
            NSLog(@"Course not added");
    }
}

Your IBAction keep it simple there you don't want to fire off life cycle event from an IBAction instead call the methods you need not to mention that it is not a good idea to call viewDidLoad before viewWillAppear Method...

- (IBAction)addNewCourse:(id)sender {
   [self addCourse];
   [self loadCourses];
}

Upvotes: 1

Ilesh P
Ilesh P

Reputation: 4036

first you check the array data it valid or not .(put break point and check it) and i think u got error because u still not convert integer to string . i replace this line in to tableview cellForRowAtIndexPath:

cell.detailTextLabel.text = dict[@"id"];

to replace

cell.detailTextLabel.text =[NSString stringWithFormat:@"%d",dict[@"id"]];

Its may be very helpful to you Thanks.

Upvotes: 0

Related Questions