DevArenaCN DevArenaCN - 3 months ago 6
iOS Question

'NSInvalidArgumentException', reason: '-[__NSCFString objectForKeyedSubscript:]: unrecognized selector sent to instance

I'm very new to Obj-c and I'm now creating a tableview to show what I have parsed from Json. Here's the code:

#import "ClasstableViewController.h"
@interface ClasstableViewController ()
@end
@implementation ClasstableViewController

- (void)viewDidLoad {
[super viewDidLoad];

self.title = @"JSONRead";
NSString *testUrl = @"example.com";
NSURL *url = [NSURL URLWithString:testUrl];

NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10];

NSData *JSONData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSArray *jsonResult = [NSJSONSerialization JSONObjectWithData:JSONData options:kNilOptions error:nil];
self.data = jsonResult;
NSMutableArray *_names = [NSMutableArray array];

for (id item in jsonResult)
[_names addObject:[NSString stringWithFormat:@"%@", item[@"Mon"]]];

self.names = _names;
}

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

// Return the number of sections.
return 1;
}

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

// Return the number of rows in the section.
return [self.names count];
}

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

static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (!cell)
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

cell.textLabel.text = self.names[indexPath.row];

return cell;
}


and I have change my tableview to the correct class in the identity inspector to ClasstableViewController, I see others have resolve their issues with this solution.

but I'm still getting this:

-[__NSCFString objectForKeyedSubscript:]: unrecognized selector sent to instance 0x7fd8835691c0
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString objectForKeyedSubscript:]: unrecognized selector sent to instance 0x7fd8835691c0'


anyone have any idea why? Please help me

Answer

Probably your NSArray *jsonResult is an array of NSStrings, or contain some NSStrings as objects. So when you do

for (id item in jsonResult)
    [_names addObject:[NSString stringWithFormat:@"%@", item[@"Mon"]]];

you are supposing that item is a NSDictionary, but it isn't.