Parsing JSON image urls in iOS error - ios

I'm trying to parse a JSON file containing some links to images and some titles and times.
This is my code:
#import "PicturesViewController.h"
#import "DemoViewController.h"
#import "SecondViewController.h"
#import "AppDelegate.h"
#import "RNBlurModalView.h"
#import "PictureJSON.h"
#import "HMSegmentedControl.h"
#interface PicturesViewController ()
{
NSInteger refreshIndex;
NSArray *images;
}
#end
#implementation PicturesViewController
- (void)viewDidLoad
{
HMSegmentedControl *segmentedControl = [[HMSegmentedControl alloc] initWithSectionTitles:#[#"Instagram", #"Hashtags", #"Facebook"]];
[segmentedControl setFrame:CGRectMake(10, 10, 300, 60)];
[segmentedControl addTarget:self action:#selector(segmentedControlChangedValue:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:segmentedControl];
[super viewDidLoad];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Menu" style:UIBarButtonItemStyleBordered target:self action:#selector(showMenu)];
UIPanGestureRecognizer *gestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(swipeHandler:)];
[self.view addGestureRecognizer:gestureRecognizer];
[self issueLoadRequest];
}
- (void)swipeHandler:(UIPanGestureRecognizer *)sender
{
[[self sideMenu] showFromPanGesture:sender];
}
- (void)segmentedControlChangedValue:(HMSegmentedControl *)segmentedControl1 {
[self issueLoadRequest];
}
- (void)segmentedControlSelectedIndexChanged:(id)sender
{
[self issueLoadRequest];
}
#pragma mark -
#pragma mark Button actions
- (void)showMenu
{
[[self sideMenu] show];
}
#pragma mark - Table view data source
- (void)issueLoadRequest
{
// Dispatch this block asynchronosly. The block gets JSON data from the specified URL and performs the proper selector when done.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://my-site/pictureparse.php?name=Name"]];
[self performSelectorOnMainThread:#selector(receiveData:) withObject:data waitUntilDone:YES];
});
}
- (void)receiveData:(NSData *)data {
// When we have the data, we serialize it into native cocoa objects. (The outermost element from twitter is
// going to be an array. I JUST KNOW THIS. Reload the tableview once we have the data.
self.tweets = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
[self.myTableView reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.tweets.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"PictureJSON";
PictureJSON *cell = (PictureJSON *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"PictureJSON" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
// The element in the array is going to be a dictionary. I JUST KNOW THIS. The key for the tweet is "text".
NSDictionary *tweet = [self.tweets objectAtIndex:indexPath.row];
NSLog(#"%#", [cell class]);
cell.instaImage = [tweet objectForKey:#"link"];
cell.titleLabel.text = [tweet objectForKey:#"title"];
cell.timeLabel.text = [tweet objectForKey:#"published"];
return cell;
}
But when I launch my app I get this error:
Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<PicturesViewController 0x758bf70> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key instaImage.'
My JSON-file looks like this:
[
{
"link": "http://link.com/picture.jpg",
"title": "title",
"published": "0:12 PM 21/10"
},
{
"link": "http://link.com/picture.jpg",
"title": "title",
"published": "0:09 AM 21/10"
}
]
What am I doing wrong?

I think you have to check the property instaImage. I think you are accessing the property that you have not defined in nib.

Fist try to debug this . From the crash log I think you are doing wrong with the custom cell . first check your connection of the PictureJSON . and check your file owner it should be your custom cell. You can confirm this using breakpoint . if you get error while cell creation then above is the solution .

I think the problem is not with your JSON serialization, from your log this crash because of your static NSString *simpleTableIdentifier = #"PictureJSON";
Make sure, you have assigned your custom cell with this identifier !

Related

How can I refresh TableViewCell data with Refresh Control

I am attempting to load data into a UITableViewCell whenever the refresh control is activated. My code successfully retrieves the data and I can verify this with NSLog, but the ViewCell does not update with the new data when Refresh Control ends. Can anyone point me in the right direction?
Below is MyViewController.m file:
#define JSON_URL #"https://website.com"
#import "MyViewController.h"
#import "Object.h"
#import "MyViewCell.h"
#interface MyViewController ()
#property (nonatomic,strong) NSMutableArray *objectHolderArray;
#end
#implementation MyViewController
- (void)viewDidLoad
{
NSURL *blogURL = [NSURL URLWithString:JSON_URL];
NSData *jsonData = [NSData dataWithContentsOfURL:blogURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization
JSONObjectWithData:jsonData options:0 error:&error];
for (NSDictionary *bpDictionary in dataDictionary) {
Object *currenHotel = [[Object alloc]Station:[bpDictionary objectForKey:#"station"] Status:[bpDictionary objectForKey:#"status"]];
[self.objectHolderArray addObject:currenHotel];
}
[super viewDidLoad];
//to add the UIRefreshControl to UIView
UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:#"Please Wait..."]; //to give the attributedTitle
[refreshControl addTarget:self action:#selector(refresh:) forControlEvents:UIControlEventValueChanged];
}
- (IBAction)refresh:(UIRefreshControl *)sender {
[self viewDidLoad];
[sender endRefreshing];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
(NSInteger)section
{
return [self.objectHolderArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
MartaViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier
forIndexPath:indexPath];
Object *currentHotel = [self.objectHolderArray
objectAtIndex:indexPath.row];
cell.lblStation.text = currentHotel.station;
cell.lblStatus.text = currentHotel.status;
return cell;
}
-(NSMutableArray *)objectHolderArray{
if(!_objectHolderArray) _objectHolderArray = [[NSMutableArray alloc]init];
return _objectHolderArray;
}
#end
You need to reload your data. Implement Refreshcontroll like this:
- (void)viewDidLoad {
refreshControl = [[UIRefreshControl alloc] init];
[refreshControl addTarget:self
action:#selector(update)
forControlEvents:UIControlEventValueChanged];
[self.startScreenView addSubview:refreshControl];
}
- (void) update {
[refreshControl beginRefreshing];
[yourTableView reloadData];
[refreshControl endRefreshing];
}
You do not actually modify, nor reload the table view and its data in any way in the refresh function. You should update the data source of your table view and then call [tableView reloadData]; after the update.

retaining data outside of viewDidLoad in objective c ios

I am aware this question has been asked previously, but the answers provided have not solved my issue.
For instance, I have a very simple array of objects outlined in viewDidLoad:
#implementation MyViewController {
NSArray *tableData;
}
- (void)viewDidLoad
{
[super viewDidLoad];
tableData = [NSArray arrayWithObjects:#"Hello", #"My", #"Name", #"Is"];
NSLog(#"My Data: %#", tableData);
which is called in a tableView using cellForRowAtIndexPath
cell.nameLabel.text = [tableData objectAtIndex:indexPath.row];
This works fine and the NSLog shows my array. However, when i outline tableData outside of viewDidLoad, my array is (null).
My question is, how do I make my array available for the tableView when it is specified outside of ViewDidLoad?
edit: Here is my specific code:
#import <UIKit/UIKit.h>
#import "PhotoView.h"
#interface FrontViewController : UIViewController
#property (nonatomic, retain) UITableView *tableView;
#end
#import "FrontViewController.h"
#import "StreamScreen.h"
#import "API.h"
#import "PhotoView.h"
#import "StreamPhotoScreen.h"
#import "PrivateViewController.h"
#import "SWRevealViewController.h"
#import "PhotoScreen.h"
#import "RearViewController.h"
#import "SimpleTableCell.h"
#interface FrontViewController()
// Private Methods:
- (IBAction)pushExample:(id)sender;
#end
#implementation FrontViewController{
NSArray *tableData;
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = NSLocalizedString(#"Front View", nil);
SWRevealViewController *revealController = [self revealViewController];
[self.navigationController.navigationBar addGestureRecognizer:revealController.panGestureRecognizer];
UIBarButtonItem *revealButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:#"reveal-icon.png"]
style:UIBarButtonItemStyleBordered target:revealController action:#selector(revealToggle:)];
self.navigationItem.leftBarButtonItem = revealButtonItem;
// This works if I uncomment
//tableData = [NSArray arrayWithObjects:#"Hello", #"My", #"Name", #"Is", nil];
[self refreshStream];
}
-(void)refreshStream {
// call the "stream" command from the web API
[[API sharedInstance] commandWithParams:
[NSMutableDictionary dictionaryWithObjectsAndKeys:#"stream", #"command", nil]
onCompletion:^(NSDictionary *json) {
//got stream
[self showStream:[json objectForKey:#"result"]];
NSMutableArray *myData = [[NSMutableArray alloc] init];
myData = [json objectForKey:#"result"];
NSArray *userNameData = [myData valueForKey:#"username"];
[self loadData];
tableData = userNameData;
[self.tableView reloadData];
// I can see my json array in NSLog
NSLog(#"here's the results: %#", tableData);
}];
}
//This doesn't work either
//-(void)loadData {
// Add the data to your array.
//tableData = [NSArray arrayWithObjects:#"Hello", #"My", #"Name", #"Is", nil];
//NSLog(#"My Data: %#", tableData);
// Now load the table view.
// [self.tableView reloadData];
//}
-(void)showStream:(NSArray*)stream {
for (int i=0;i<[stream count];i++) {
NSDictionary* photo = [stream objectAtIndex:i];
}
NSArray *checkData = [stream valueForKey:#"username"];
//I can see my data in NSLog
NSLog(#"here's the results: %#", checkData);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [tableData count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 78;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"SimpleTableCell";
SimpleTableCell *cell = (SimpleTableCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"SimpleTableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.nameLabel.text = [tableData objectAtIndex:indexPath.row];
cell.thumbnailImageView.image = [UIImage imageNamed:[thumbnails objectAtIndex:indexPath.row]];
cell.prepTimeLabel.text = [prepTime objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"didSelectRowAtIndexPath");
/*UIAlertView *messageAlert = [[UIAlertView alloc]
initWithTitle:#"Row Selected" message:#"You've selected a row" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];*/
UIAlertView *messageAlert = [[UIAlertView alloc]
initWithTitle:#"Row Selected" message:[tableData objectAtIndex:indexPath.row] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
// Display the Hello World Message
[messageAlert show];
// Checked the selected row
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"willSelectRowAtIndexPath");
if (indexPath.row == 0) {
return nil;
}
return indexPath;
}
#end
-(void)refreshStream {
// call the "stream" command from the web API
[[API sharedInstance] commandWithParams:
[NSMutableDictionary dictionaryWithObjectsAndKeys:#"stream", #"command", nil]
onCompletion:^(NSDictionary *json) {
//got stream
[self showStream:[json objectForKey:#"result"]];
NSMutableArray *myData = [json objectForKey:#"result"];
NSArray *userNameData = [myData valueForKey:#"username"];
}];
tableData = userNameData;
[self.tableView reloadData];
}
You're falling into a very common trap with asynchronous programming here.
commandWithParams takes a completion block, which is where you are getting the data out of the JSON. This block is not executed until the API call has returned. The sequence of events that happens when you run this code is:
commandWithParams is called
tableData is assigned to the contents of userNameData (which presumably you've also declared somewhere else otherwise this would not even compile)
reloadData is called
.... time passes
The completion block is executed and the JSON is read out into local variables, which are then instantly destroyed.
You need to move the two lines (points 2 and 3 in the list above) inside the completion block. There will be no data for your table until the block returns.
Ok my understanding of your question is that you want to assign variables to your NSArray in another method (not viewDidLoad) and then load the table view.
This is simple, just make a method which is in charge of adding the data to your array and then reload your table view like so:
-(void)viewDidLoad {
[super viewDidLoad];
// Call your method.
[self loadData];
}
-(void)loadData {
// Add the data to your array.
tableData = [NSArray arrayWithObjects:#"Hello", #"My", #"Name", #"Is"];
NSLog(#"My Data: %#", tableData);
// Now load the table view.
[myTableView reloadData];
}
Update 1
It would be much more helpful if you could share your code with us. How your and setting up your tableview, when its being called/etc....
Update 2
Ok well it seems obvious what yoru issue is. Your table view will never load like that. You need to call the tableview reloadData method outside the cellForRowAtIndexPath method.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *simpleTableIdentifier = #"SimpleTableCell";
SimpleTableCell *cell = (SimpleTableCell *)[self.tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"SimpleTableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.nameLabel.text = [tableData objectAtIndex:indexPath.row];
cell.thumbnailImageView.image = [UIImage imageNamed:[thumbnails objectAtIndex:indexPath.row]];
cell.prepTimeLabel.text = [prepTime objectAtIndex:indexPath.row];
return cell;
}
So the method call [self.tableView reloadData]; should only be called in your refreshStream method.
Update 3
You need to initialize your NSMutableArray before you can add data to it. initialize it in your refreshStrem method like so:
-(void)refreshStream {
// call the "stream" command from the web API
[[API sharedInstance] commandWithParams:[NSMutableDictionary dictionaryWithObjectsAndKeys:#"stream", #"command", nil] onCompletion:^(NSDictionary *json) {
//got stream
[self showStream:[json objectForKey:#"result"]];
NSMutableArray *myData = [[NSMutableArray alloc] init];
myData = [json objectForKey:#"result"];
NSArray *userNameData = [myData valueForKey:#"username"];
}];
tableData = userNameData;
[self.tableView reloadData];
}
Update 4
Ok well after reading #jrturton answer, I think its safe to assume that my answer is rubbish. To anyone reading my answer, please view #jrturton post.
Well I feel pretty sheepish. The answer was simple. I was so hung up on Json and API that all I didn't check the basics. All I need was in my .h file:
#property (strong, nonatomic) IBOutlet UITableView *tableView;
I had originally had:
#property (nonatomic, retain) UITableView *tableView;

Parsing JSON link in Objective C error

I'm trying to parse a JSON file containing urls to images.
My code:
NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:#"http://my-site/pictureparse.php?name=Name"]];
NSData *data= [NSData dataWithContentsOfURL:URL];
if (data == nil) {
return;
}
NSError* error;
NSMutableDictionary *jsonIs = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error];
NSLog(#"Json : %#",jsonIs);
if (jsonIs != nil) {
NSString *item_media = [jsonIs objectForKey:#"link"];
where "link" is the link to the image in the JSON-file.
The JSON structure looks like this:
[
{
"link": "http://link-to-image.com/picture.jpg",
"title": "Title",
"published": "0:01 PM 24/10"
},
{
"link": "http://link-to-image.com/picture.jpg",
"title": "Title",
"published": "0:01 PM 24/10"
},
{
"link": "http://link-to-image.com/picture.jpg",
"title": "Title",
"published": "0:01 PM 24/10"
},
{
"link": "http://link-to-image.com/picture.jpg",
"title": "Title",
"published": "0:08 PM 23/10"
}
]
When I launch the app I see in NSLog that it parses the objects, but I get the error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x16e81ed0
How can I take these parsed objects/links and display them in a feed, like Instagram?
I have tried with the following code, but it doesn't work...
#import "PicturesViewController.h"
#import "DemoViewController.h"
#import "SecondViewController.h"
#import "AppDelegate.h"
#import "RNBlurModalView.h"
#import "PictureJSON.h"
#import "HMSegmentedControl.h"
#interface PicturesViewController ()
{
NSInteger refreshIndex;
NSArray *images;
}
#end
#implementation PicturesViewController
- (void)viewDidLoad
{
HMSegmentedControl *segmentedControl = [[HMSegmentedControl alloc] initWithSectionTitles:#[#"Instagram", #"Hashtags", #"Facebook"]];
[segmentedControl setFrame:CGRectMake(10, 10, 300, 60)];
[segmentedControl addTarget:self action:#selector(segmentedControlChangedValue:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:segmentedControl];
[super viewDidLoad];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Menu" style:UIBarButtonItemStyleBordered target:self action:#selector(showMenu)];
UIPanGestureRecognizer *gestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(swipeHandler:)];
[self.view addGestureRecognizer:gestureRecognizer];
[self issueLoadRequest];
}
- (void)swipeHandler:(UIPanGestureRecognizer *)sender
{
[[self sideMenu] showFromPanGesture:sender];
}
- (void)segmentedControlChangedValue:(HMSegmentedControl *)segmentedControl1 {
[self issueLoadRequest];
}
- (void)segmentedControlSelectedIndexChanged:(id)sender
{
[self issueLoadRequest];
}
#pragma mark -
#pragma mark Button actions
- (void)showMenu
{
[[self sideMenu] show];
}
#pragma mark - Table view data source
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"PictureJSON";
PictureJSON *cell = (PictureJSON *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"PictureJSON" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
// The element in the array is going to be a dictionary. I JUST KNOW THIS. The key for the tweet is "text".
NSDictionary *tweet = [self.tweets objectAtIndex:indexPath.row];
NSLog(#"%#", [cell class]);
UIImageView *instaImage = [[UIImageView alloc] init];
instaImage.image = [tweet objectForKey:#"link"];
cell.titleLabel.text = [tweet objectForKey:#"title"];
cell.timeLabel.text = [tweet objectForKey:#"published"];
return cell;
}
- (void)issueLoadRequest
{
// Dispatch this block asynchronosly. The block gets JSON data from the specified URL and performs the proper selector when done.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://my-site.com/picutreparse.php?name=Name"]];
[self performSelectorOnMainThread:#selector(receiveData:) withObject:data waitUntilDone:YES];
});
}
- (void)receiveData:(NSData *)data {
// When we have the data, we serialize it into native cocoa objects. (The outermost element from twitter is
// going to be an array. I JUST KNOW THIS. Reload the tableview once we have the data.
self.tweets = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
[self.myTableView reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.tweets.count;
}
#end
I would really appreciate a solution!
The problem is that the object you get from your parsing is a NSArray and not a NSDictionary.
Edit your code to this one:
#interface PicturesViewController ()
{
// ...
NSArray *items;
}
At the point where you get the data:
items = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
Finally:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// ...
NSDictionary *item = [items objectAtIndex:indexPath.row];
NSString *item_media = [item objectForKey:#"link"];
// ...
}
What is wrong you make NSMutableDictionary
NSMutableArray *jsonIs = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error];
NSLog(#"Json : %#",jsonIs);
if (jsonIs != nil) {
NSMutableDictionary* aDict = jsonIs[0];
NSString *item_media = [aDict objectForKey:#"link"];
}
your main JSON is an array because of "[...]" in this array you got dictionaries : "{..}"
edit for tableView question:
make the NSMutableArray *jsonIs to global
#implementation PicturesViewController{
NSMutableArray *jsonIs
}
then in tableview delegate:
NSString *item_media = [jsonIs[indexPath.row] objectForKey:#"link"];

Parsing JSON image urls to custom Table View error

I'm trying to parse a JSON file containing some url's to pictures, titles and texts. I've tried to parse another JSON file in the same way, but only with text and it works. But this one will not work. Here's my code:
.h:
#import <UIKit/UIKit.h>
#interface PicturesViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>{
NSURLConnection *conn;
NSMutableData *responseData;
NSMutableArray *news;
NSIndexPath * indexPath;
UIActivityIndicatorView *loading;
}
#property (nonatomic, retain) NSIndexPath * indexPath;
#property (nonatomic, strong) NSArray *tweets;
#property (strong, nonatomic) IBOutlet UITableView *myTableView;
#end
.m:
#import "PicturesViewController.h"
#import "AppDelegate.h"
#import "RNBlurModalView.h"
#import "PictureJSON.h"
#interface PicturesViewController ()
{
NSInteger refreshIndex;
NSArray *images;
}
#end
#implementation PicturesViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Menu" style:UIBarButtonItemStyleBordered target:self action:#selector(showMenu)];
UIPanGestureRecognizer *gestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(swipeHandler:)];
[self.view addGestureRecognizer:gestureRecognizer];
[self issueLoadRequest];
}
- (void)swipeHandler:(UIPanGestureRecognizer *)sender
{
[[self sideMenu] showFromPanGesture:sender];
}
#pragma mark -
#pragma mark Button actions
- (void)showMenu
{
[[self sideMenu] show];
}
#pragma mark - Table view data source
- (void)issueLoadRequest
{
// Dispatch this block asynchronosly. The block gets JSON data from the specified URL and performs the proper selector when done.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://my-site/pictureparse.php?name=MyName"]];
[self performSelectorOnMainThread:#selector(receiveData:) withObject:data waitUntilDone:YES];
});
}
- (void)receiveData:(NSData *)data {
// When we have the data, we serialize it into native cocoa objects. (The outermost element from twitter is
self.tweets = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
[self.myTableView reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.tweets.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"PictureJSON";
PictureJSON *cell = (PictureJSON *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"PictureJSON" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
NSDictionary *tweet = [self.tweets objectAtIndex:indexPath.row];
cell.instaImage = [tweet objectForKey:#"link"];
cell.titleLabel.text = [tweet objectForKey:#"title"];
cell.timeLabel.text = [tweet objectForKey:#"published"];
return cell;
}
#end
I have a custom table view file named PictureJSON with a nib file which looks like this:
But when I launch my app I get this error:
Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<PicturesViewController 0x17d86dc0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key instaImage.'
Can someone help me fix this?
Thanks!
Probably the JSON you got not have good structure, check the result of the query in JSONLint - The JSON Validator perhaps this can help you to detect the error.

EXC_BAD_ACCESS with NSXMLParser and ARC

Beginner in iOS development, I'll try to realize an application which displays an RSS feed by an XML file.
In the viewDidLoad of my UITableView class, I'm using an UIActivityIndicator to wait until the data is loading.
But, at the moment that the app will be back to the main thread, I've an EXC_BAC_ACCESS code 2 at the end of the parseXMLStart function. I don't understand why...
Here the error message:
Thread 6 : 0-[NSXMLParser dealloc]
Message : EXC_BAC_ACCESS (code=2, address=0xc)
Line : 0xbb0840: movl (%eax,%ecx), %ecx
I don't know what and where is my error. How can I fix it?
Here is my code:
=> Class Type :: UITableViewController
>> Header
#interface DataListViewController : UITableViewController {
UIActivityIndicatorView *activityView;
NSMutableArray *dataFromXML;
}
- (void)parseXMLStart;
- (void)parseXMLDone;
#end
>> Main
#implementation DataListViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.title = #"View 1";
activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
activityView.center = self.view.center;
[self performSelectorInBackground:#selector(parseXMLStart) withObject:nil];
[activityView startAnimating];
[activityView setHidesWhenStopped:YES];
[self.view addSubview:activityView];
}
#pragma mark - UIActivityIndicator Methods
- (void)parseXMLStart
{
// To Show the animation
sleep(1);
dataFromXML = [[NSMutableArray alloc] init];
// COMMENT TO TEST /*
[dataFromXML addObject:#"Element 1"];
[dataFromXML addObject:#"Element 2"];
[dataFromXML addObject:#"Element 3"];
// */ COMMENT TO TEST
// ------------------------------------------------------------------------------------------------------------------------------------
// UNCOMMENT TO TEST
/*
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"words" ofType:#"xml"];
NSURL *url = [[NSURL alloc] initWithString:[[NSString stringWithFormat:#"file://%#",filePath] stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
XML2ObjectParser *parserWords = [[XML2ObjectParser alloc] parseXMLAtURL:url toObject:#"Word" parseError:nil];
NSLog(#">> parserWords Items Count :: %i", parserWords.items.count);
for (int i = 0; i < [parserWords.items count]-1; i++) {
Word *aWord = [[Word alloc] init];
aWord = (Word *)[[parserWords items] objectAtIndex:i];
[dataFromXML addObject:aWord];
}
NSLog(#">> dataFromXML Count :: %i", dataFromXML.count);
*/
// UNCOMMENT TO TEST
// --------------------------------------------------------------------------------------------------------------------------------------------
// EXC_BAD_ACCESS (code=2, address=0xc)
// Thread 6 : 0-[NSXMLParser dealloc]
// 0xbad840: movl (%eax,%ecx), %ecx
// --------------------------------------------------------------------------------------------------------------------------------------------
[self performSelectorOnMainThread:#selector(parseXMLDone) withObject:nil waitUntilDone:YES];
}
- (void)parseXMLDone
{
[activityView stopAnimating];
[self.tableView reloadData];
}
# pragma mark - Table View Method
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [dataFromXML count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellID = #"CellID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
}
cell.textLabel.text = [dataFromXML objectAtIndex:[indexPath row]];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
DataListDetailViewController *_dataListDetailViewController = [[DataListDetailViewController alloc] init];
_dataListDetailViewController.title = [dataFromXML objectAtIndex:[indexPath row]];
[self.navigationController pushViewController:_dataListDetailViewController animated:YES];
}
#end
It looks to me like your selector is typed incorrectly. you have #selector(parsingXMLDone) and it should be #selector(parseXMLDone)
I've find the error.
It wasn't my mistake but the ARC.
I'm explain, when parsing XML it's finished, the background thread is killed and after ARC wants to dealloc the NSXMLParser.
That's why, it causes an EXC_BAD_ACCESS, Because ARC want to dealloc an already deallocated object (AKA NSXMLParser).
The solution was to compile my class without ARC, using the flag "fno-objc-arc" in the Build Phases of the Target.
See : NSXMLParser gives EXC_BAD_ACCESS only with ARC enabled
Thanks for the help.

Resources