Putting my JSON into a tableView - iphone

what i'm currently trying to do is get my json information (twitter user timeline) and stick it into a table, everything about it json works, but when it comes to adding the information to the tableView it doesn't do anything about it, Here is my code :
#import "FirstViewController.h"
#import <Twitter/Twitter.h>
#import <Accounts/Accounts.h>
#interface FirstViewController ()
- (void)fetchData;
#end
#implementation FirstViewController
#synthesize timelineTwiter = _timelineTwiter;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(#"First", #"First");
self.tabBarItem.image = [UIImage imageNamed:#"first"];
}
return self;
}
-(void)fetchData {
ACAccountStore *store = [[ACAccountStore alloc] init];
ACAccountType *twitterAccountType =
[store accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[store requestAccessToAccountsWithType:twitterAccountType
withCompletionHandler:^(BOOL granted, NSError *error) {
if (!granted) {
NSLog(#"User rejected access to his account.");
}
else {
NSArray *twitterAccounts =
[store accountsWithAccountType:twitterAccountType];
if ([twitterAccounts count] > 0) {
ACAccount *account = [twitterAccounts objectAtIndex:0];
NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
[params setObject:#"1" forKey:#"include_entities"];
NSURL *url =
[NSURL
URLWithString:#"http://api.twitter.com/1/statuses/home_timeline.json"];
TWRequest *request =
[[TWRequest alloc] initWithURL:url
parameters:params
requestMethod:TWRequestMethodGET];
[request setAccount:account];
[request performRequestWithHandler:
^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if (!responseData) {
NSLog(#"%#", error);
}
else {
NSError *jsonError;
NSArray *timeline = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&jsonError];
self.timelineTwiter = timeline;
if (timeline) {
NSDictionary* tweets0 = [timeline objectAtIndex:0];
NSLog(#"%#", [tweets0 objectForKey:#"text"]);
NSLog(#"%#", [[tweets0 objectForKey:#"user"] objectForKey:#"screen_name"]);
NSDictionary* tweets1 = [timeline objectAtIndex:1];
NSLog(#"%#", [tweets1 objectForKey:#"text"]);
NSLog(#"%#", [[tweets1 objectForKey:#"user"] objectForKey:#"screen_name"]);
NSDictionary* tweets2 = [timeline objectAtIndex:2];
NSLog(#"%#", [tweets2 objectForKey:#"text"]);
NSLog(#"%#", [[tweets2 objectForKey:#"user"] objectForKey:#"screen_name"]);
}
else {
NSLog(#"%#", jsonError);
}
}
}];
}
}
}];
}
-(IBAction)refreshTimeline:(id)sender {
[self fetchData];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 0;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.timelineTwiter count];
}
- (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];
}
id userTimeline = [self.timelineTwiter objectAtIndex:[indexPath row]];
cell.textLabel.text = [userTimeline objectForKey:#"text"];
cell.detailTextLabel.text = [userTimeline valueForKeyPath:#"user.name"];
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self fetchData];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewWillAppear:(BOOL)animated
{
[self fetchData];
[super viewWillAppear:animated];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#end
but it never loads the data into the table view, any help?
Side note:
I am using it with interface builder.
& Ideally i'd like to make a custom cell so i could work out the layout each cell, so if you know of any good sites which will show how to do that, that'd also be a big hand.

you have to return at least one section to the table at a minimum. right now you are return zero sections.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 0;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}

You missed the reloadData at the end of your fetchData implementation.

Related

Xcode live news feed with multiple accounts or user

Im new to xcode.
and Im creating this facebook, twitter, instagram and youtube news feed in a tableview
at first Im trying this facebook to load multiple json
#import "ViewController.h"
#import "DetailViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#define kQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
#define kJSONUrl [NSURL URLWithString:#"https://www.facebook.com/feeds/page.php?id=1387524391527078&format=json"]
#define kJSONUrl1 [NSURL URLWithString:#"https://www.facebook.com/feeds/page.php?id=196934133652011&format=json"]
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
#interface ViewController ()
#end
#implementation ViewController
#synthesize jsonTitles,table,jsonContent;
-(void)loadJSON:(NSData *)responseData {
NSError *error;
NSArray *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSArray *array = [json valueForKey:#"entries"];
for (int i = 0; i < array.count; i++) {
NSArray *entry = [array objectAtIndex:i];
NSString *title = [entry valueForKey:#"title"];
NSString *content = [entry valueForKey:#"content"];
[jsonTitles addObject:title];
[jsonContent addObject:content];
}
[self.table reloadData];
}
- (void)viewDidLoad
{
self.table.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"background.png"]];
jsonTitles = [[NSMutableArray alloc]init];
jsonContent = [[NSMutableArray alloc]init];
dispatch_async(kQueue, ^{
NSData *data = [NSData dataWithContentsOfURL:kJSONUrl];
[self performSelectorOnMainThread:#selector(loadJSON:) withObject:data waitUntilDone:YES];
NSData *data1 = [NSData dataWithContentsOfURL:kJSONUrl1];
[self performSelectorOnMainThread:#selector(loadJSON:) withObject:data1 waitUntilDone:YES];
});
[super viewDidLoad];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 40;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [jsonTitles count];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self performSegueWithIdentifier:#"detailSegue" sender:nil];
// NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:#"detailSegue" ascending:YES];
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"detailSegue"]) {
DetailViewController *detail = segue.destinationViewController;
NSIndexPath *path = [self.table indexPathForSelectedRow];
detail.titleText = [jsonTitles objectAtIndex:path.row];
detail.contentText = [jsonContent objectAtIndex:path.row];
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *tableCellID = #"tableCellID";
// UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:tableCellID];
UITableViewCell *cell =[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:tableCellID];
NSString *myurl = #"http://graph.facebook.com/idoltap/picture";
NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:myurl]];
UIImage *myimage = [[UIImage alloc] initWithData:imageData];
cell.imageView.image = myimage;
// cell.imageView.image = [UIImage imageNamed:#"background.png"];
cell.textLabel.text = #"iDOLTap";
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tableCellID];
}
cell.detailTextLabel.text = [jsonTitles objectAtIndex:indexPath.row];
if ([cell.detailTextLabel.text isEqual: #" "]) {
cell.detailTextLabel.text = [jsonContent objectAtIndex:indexPath.row];
}
return cell;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Is my pattern correct?
I dont know how I can load the right profile picture for each json/user and sort it by its published date.
I just want some help to fix this one in the right way.

UITableView Crashing

I have a UITableView I add as a subview of self.view and it crashes at
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
Here is my code:
interface (in CRFeedViewController.m)
#property (assign) BOOL dataIsLoaded;
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(dataIsLoaded == YES)
{
return [self.items count];
}
else {
return 1;
}
}
// Return a cell for the index path
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"cell";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Cell label
cell.textLabel.text = #"Tweet";
if (cell == nil) {
cell = [[UITableViewCell alloc] init];
}
return cell;
}
- (void)getTimeLine {
ACAccountStore *account = [[ACAccountStore alloc] init];
ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[account requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error)
{
if (granted == YES)
{
NSArray *arrayOfAccounts = [account accountsWithAccountType:accountType];
if ([arrayOfAccounts count] > 0)
{
ACAccount *twitterAccount = [arrayOfAccounts lastObject];
NSURL *requestURL = [NSURL URLWithString:#"http://api.twitter.com/1/statuses/home_timeline.json"];
NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
[parameters setObject:#"20" forKey:#"count"];
[parameters setObject:#"1" forKey:#"include_entities"];
SLRequest *postRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:requestURL parameters:parameters];
postRequest.account = twitterAccount;
[postRequest performRequestWithHandler: ^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
self.items = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error];
if (self.items.count != 0) {
dataIsLoaded = YES;
[self.tableView reloadData];
}
else {
NSLog(#"No items");
}
}];
}
} else {
NSLog(#"No access");
}
}];
}
- (void) viewWillAppear:(BOOL)animated
{
[self getTimeLine];
}
- (void)viewDidLoad
{
[super viewDidLoad];
/**
* TABLE VIEW
* Add subview of the table
*/
self.items = [NSArray arrayWithObjects:#"test", nil];
CGRect tableViewRect = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
UITableView *tableView = [[UITableView alloc] initWithFrame:tableViewRect style:UITableViewStylePlain];
tableView.dataSource = self;
[self.view addSubview:tableView];
}
EDIT
Here is my complete code, I'm sorry I don't understand all of this yet, I am still very new.
.h
//
// CRFeedViewController.h
// Twitter
//
// Created by Cody Robertson on 6/27/13.
// Copyright (c) 2013 Cody Robertson. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <Accounts/Accounts.h>
#import <Social/Social.h>
#interface CRFeedViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
#property (strong, nonatomic) UITableView *tableView;
#property (strong, nonatomic) NSArray *items;
#end
.m
//
// CRFeedViewController.m
// Twitter
//
// Created by Cody Robertson on 6/27/13.
// Copyright (c) 2013 Cody Robertson. All rights reserved.
//
#import "CRFeedViewController.h"
#import "CRComposeViewController.h"
#import "CRSearchViewController.h"
#interface CRFeedViewController ()
#property (assign) BOOL dataIsLoaded;
- (void) composeTweet: (id) sender;
- (void) searchTweets: (id) sender;
- (void) getTimeLine;
#end
#implementation CRFeedViewController
#synthesize dataIsLoaded;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
/**
* NAV BAR
* Add icon and button to nav bar
*/
// Add Twitter Icon as Title
UIImageView *UINavTitleLogo = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"UINavBarLogo.png"]];
UINavTitleLogo.contentMode = UIViewContentModeScaleAspectFill;
self.navigationItem.titleView = UINavTitleLogo;
// Add Search & Compose Icon
UIImage *UISearchNavButton = [UIImage imageNamed:#"Search.png"];
UIBarButtonItem *CRSearchNavButton = [[UIBarButtonItem alloc] initWithImage:UISearchNavButton style:UIBarButtonItemStylePlain target:self action:#selector(searchTweets:)];
UIImage *UIComposeNavButton = [UIImage imageNamed:#"Compose.png"];
UIBarButtonItem *CRComposeNavButton = [[UIBarButtonItem alloc] initWithImage:UIComposeNavButton style:UIBarButtonItemStylePlain target:self action:#selector(composeTweet:)];
NSArray *UINavItems = #[CRComposeNavButton, CRSearchNavButton];
self.navigationItem.rightBarButtonItems = UINavItems;
[[UINavigationBar appearance] setTitleTextAttributes:#{
UITextAttributeTextColor: [UIColor whiteColor]
}];
/**
* TAB BAR
* Add icon and label to task bar
*/
UIImage *CRFeedTabBarIcon = [UIImage imageNamed:#"Home.png"];
UITabBarItem *CRFeedTabBarItem = [[UITabBarItem alloc] initWithTitle:#"Home" image:CRFeedTabBarIcon tag:0];
self.tabBarItem = CRFeedTabBarItem;
}
return self;
}
- (void) composeTweet:(id)sender
{
/**
* PUSH VIEW TO COMPOSE
* Load the compose view
*/
CRComposeViewController *CRCompose = [[CRComposeViewController alloc] init];
CRCompose.title = #"New Tweet";
[self.navigationController pushViewController:CRCompose animated:YES];
}
- (void) searchTweets:(id)sender
{
/**
* PUSH VIEW TO SEARCH
* Load the search view
*/
CRSearchViewController *CRSearch = [[CRSearchViewController alloc] init];
CRSearch.title = #"Search";
[self.navigationController pushViewController:CRSearch animated:YES];
}
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(dataIsLoaded == YES)
{
return [self.items count];
}
else {
return 1;
}
}
// Return a cell for the index path
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"cell";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Cell label
cell.textLabel.text = #"Tweet";
if (cell == nil) {
cell = [[UITableViewCell alloc] init];
}
return cell;
}
- (void)getTimeLine {
ACAccountStore *account = [[ACAccountStore alloc] init];
ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[account requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error)
{
if (granted == YES)
{
NSArray *arrayOfAccounts = [account accountsWithAccountType:accountType];
if ([arrayOfAccounts count] > 0)
{
ACAccount *twitterAccount = [arrayOfAccounts lastObject];
NSURL *requestURL = [NSURL URLWithString:#"http://api.twitter.com/1/statuses/home_timeline.json"];
NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
[parameters setObject:#"20" forKey:#"count"];
[parameters setObject:#"1" forKey:#"include_entities"];
SLRequest *postRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:requestURL parameters:parameters];
postRequest.account = twitterAccount;
[postRequest performRequestWithHandler: ^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
self.items = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error];
if (self.items.count != 0) {
dataIsLoaded = YES;
[self.tableView performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:YES];
}
else {
NSLog(#"No items");
}
}];
}
} else {
NSLog(#"No access");
}
}];
}
- (void) viewWillAppear:(BOOL)animated
{
[self getTimeLine];
}
- (void)viewDidLoad
{
[super viewDidLoad];
/**
* TABLE VIEW
* Add subview of the table
*/
self.items = [NSArray arrayWithObjects:#"test", nil];
CGRect tableViewRect = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
UITableView *tableView = [[UITableView alloc] initWithFrame:tableViewRect style:UITableViewStylePlain];
tableView.delegate = self;
tableView.dataSource = self;
[self.view addSubview:tableView];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
You should call the reloadData method on the main thread:
[self.tableView performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:YES];
Not sure if this is causing your crash, but you need to init your cells with the reuse identifier:
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier;
I would recommend that you post the trace logged in Xcode when the app crashes. It will give a better understanding as to why your app is crashing.
Add the delegate first so those methods are ran. Don't forget to subscribe to the delegate in your .h as well.
ViewController.h
#interface ViewController : UIViewController <UITableViewDelegate,UITableViewDataSource>
#property (nonatomic, strong) NSArray *items;
// In your viewDidLoad
tableView.dataSource = self;
tableView.delegate = self;
You return 1 cell even if you don't have data. You should return 0
If the error is happening in the numberOfRows method, then the culprit is most likely:
[self.items count];
The most likely case this causes an error is if self.items does not have a count method. In your viewDidLoad, you set it to an NSArray, which does have a count method. However, there is one other place you set self.items:
self.items = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error];
The result of that method most likely does not have a count method, and therefore is not an NSArray, yet you are storing it in a variable that is defined as NSArray.
After that line, above, put the following code:
NSLog(#"Class: %#", NSStringFromClass([self.items class]));
If the output is not NSArray, you most likely have a programming error.
Also, it looks like you are using multiple threads, to read/write to the same variable. This is usually not a good idea without implementing some sort of thread safety on those properties.

Login ID and Password using core data iOS

I am creating doing a project with core data.
Now my first view is Login/password in table view controller.
As soon as the user hits done, i want my app to compare the login and password text fields with the Entity Login (with attributes : userid and password) and then display another view with the informations associated with that user (1 to 1) relationship.
Can any one help me with how to validate the login password and then display only the information associated with that user?
Any help would be really appreciated. I am totally new to this.
You need to create a Fetch request against that Entity (you will need to modify this to fit your specific needs:
NSFetchRequest *request= [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Entity" inManagedObjectContext:context];
NSPredicate *predicate =[NSPredicate predicateWithFormat:#"username==%# AND password==%#",self.UsernameTextField.Text, self.PasswordTextField.Text];
[request setEntity:entity];
[request setPredicate:predicate];
... Do whatever you need to with the result (NSArray)
//first view controller
#import "ViewController.h"
#import "SecondViewController.h"
#import "SecondTableViewCell.h"
#import "AppDelegate.h"
#interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
#property(strong)NSMutableArray *company;
#end
#implementation ViewController
- (NSManagedObjectContext *)managedObjectContext
{
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:#selector(managedObjectContext)]) {
context = [delegate managedObjectContext];
}
return context;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
// Fetch the devices from persistent data store
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"CompanyDetails"];
self.company = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
[self.tableview reloadData];
}
#pragma mark-datasource
- (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.company.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"sri";
SecondTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
NSManagedObject *device = [self.company
objectAtIndex:indexPath.row];
cell.lbl_c.text=[NSString stringWithFormat:#"%#", [device valueForKey:#"companyName"]];
cell.lbl_e .text=[NSString stringWithFormat:#"%#" , [device valueForKey:#"empName"]];
cell.lbl_s .text=[NSString stringWithFormat:#"%#", [device valueForKey:#"salary"]];
cell.img_g.image =[UIImage imageWithData:[device valueForKey:#"companyImage"]];
return cell;
}
// delete
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSManagedObjectContext *context = [self managedObjectContext];
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete object from database
[context deleteObject:[self.company
objectAtIndex:indexPath.row]];
NSError *error = nil;
if (![context save:&error]) {
NSLog(#"Can't Delete! %# %#", error, [error localizedDescription]);
return;
}
// Remove device from table view
[self.company removeObjectAtIndex:indexPath.row];
[self.tableview deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"segue"]) {
NSManagedObject *selectedDevice = [self.company objectAtIndex:[[self.tableview indexPathForSelectedRow] row]];
SecondViewController *vc2 = segue.destinationViewController;
vc2.device = selectedDevice;
}
}
#end
//second view controller
#import "SecondViewController.h"
#import "AppDelegate.h"
#import <CoreData/CoreData.h>
#interface SecondViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>
#end
#implementation SecondViewController
#synthesize device;
-(NSManagedObjectContext *)managedObjectContext
{
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:#selector(managedObjectContext)]) {
context = [delegate managedObjectContext];
}
return context;
}
- (void)viewDidLoad {
[super viewDidLoad];
if (self.device) {
[self.txt_c setText:[self.device valueForKey:#"companyName"]];
[self.txt_e setText:[self.device valueForKey:#"empName"]];
[self.txt_s setText:[self.device valueForKey:#"salary"]];
self.img.image = [UIImage imageWithData:[self.device valueForKey:#"companyImage"]];
// self.txt_stdname.text = [NSString stringWithFormat:#"%#",[self.obj valueForKey:#"studentName"]];
//
// self.txt_strrollno.text = [NSString stringWithFormat:#"%#",[self.obj valueForKey:#"studentRollno"]];
//
// self.txt_stddept.text = [NSString stringWithFormat:#"%#",[self.obj valueForKey:#"studentDepartment"]];
}
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
- (IBAction)btt_save:(id)sender {
NSManagedObjectContext *context = [self managedObjectContext];
if(self.device)
{
[device setValue:self.txt_c.text forKey:#"companyName"];
[device setValue:self.txt_e.text forKey:#"empName"];
[device setValue:self.txt_s.text forKey:#"salary"];
NSData *imgdata = UIImageJPEGRepresentation(self.img.image, 0.0);
[device setValue:imgdata forKey:#"companyImage"];
}
else
{
NSManagedObject *comdetails = [NSEntityDescription insertNewObjectForEntityForName:#"CompanyDetails" inManagedObjectContext:context];
[comdetails setValue:self.txt_c.text forKey:#"companyName"];
[comdetails setValue:self.txt_e.text forKey:#"empName"];
[comdetails setValue:self.txt_s.text forKey:#"salary"];
NSData *imgdata = UIImageJPEGRepresentation(self.img.image, 0.0);
[comdetails setValue:imgdata forKey:#"companyImage"];
}
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# ", error.localizedDescription);
}
[self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)btt_gallery:(id)sender {
UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
imagePicker.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
imagePicker.delegate = self;
[self presentViewController:imagePicker animated:YES completion:nil];
}
#pragma mark UIImagePickerControllerDelegate
- (void) imagePickerController:(UIImagePickerController *)picker
didFinishPickingImage:(UIImage *)image
editingInfo:(NSDictionary *)editingInfo
{
self.img.image = image;
[self dismissModalViewControllerAnimated:YES];
}
- (IBAction)btt_cancel:(id)sender {
[self.navigationController popViewControllerAnimated:YES];
}
#end
// First view controller
#import "ViewController.h"
#import "ViewController6578.h"
#import "AppDelegate.h"
#import <CoreData/CoreData.h>
#interface ViewController ()<UITextFieldDelegate>
{
NSArray *user;
}
- (IBAction)btt_reg:(id)sender;
#end
#implementation ViewController
- (NSManagedObjectContext *)managedObjectContext
{
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:#selector(managedObjectContext)]) {
context = [delegate managedObjectContext];
}
return context;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
// AppDelegate *appDelegate =
// [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *request= [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"LogIn" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
NSPredicate *predicate =[NSPredicate predicateWithFormat:#"userName==%#",self.txt_user.text];
[request setPredicate:predicate];
NSManagedObject *manage = nil;
NSError *error;
user=[managedObjectContext executeFetchRequest:request error:&error];
if([user count]==0)
{
NSLog(#"user and password");
}
else
{
manage =user[0];
_txt_pass.text = [manage valueForKey:#"password"];
}
}
- (IBAction)btt_log:(id)sender {
if((_txt_user.text.length == 0) || (_txt_pass.text.length==0))
{
NSLog(#"enter username and password");
}
else{
NSLog(#"%#,Login successfull",_txt_user.text);
}
}
- (IBAction)btt_reg:(id)sender {
ViewController6578 *vc2 = [self.storyboard instantiateViewControllerWithIdentifier:#"ndot"];
[self.navigationController pushViewController:vc2 animated:YES];
}
#end
//second view controller
#import "ViewController6578.h"
#import "AppDelegate.h"
#import <CoreData/CoreData.h>
#interface ViewController6578 ()<UITextFieldDelegate>
#end
#implementation ViewController6578
- (NSManagedObjectContext *)managedObjectContext {
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:#selector(managedObjectContext)]) {
context = [delegate managedObjectContext];
}
return context;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
#pragma mark-delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField becomeFirstResponder];
if(textField == _txt_user)
{
[_txt_pass becomeFirstResponder];
}
else if(textField == _txt_pass)
{
[_txt_email becomeFirstResponder];
}
else if(textField == _txt_email)
{
[_txt_email becomeFirstResponder];
}
else
{
[_txt_email resignFirstResponder];
}
return YES;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField == _txt_user)
{
NSString *user =[_txt_user.text stringByReplacingCharactersInRange:range withString:string];
NSString *userRegex = #"^[A-Z0-9a-z]{6,10}$";
NSPredicate *userTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", userRegex];
if ([userTest evaluateWithObject:user] == YES)
{
_lbl1.text =#"";
}
else{
_lbl1.text =#"not valid";
}
}
if(textField ==_txt_pass)
{
NSString *pass =[_txt_pass.text stringByReplacingCharactersInRange:range withString:string];
NSString *passRegex =#"^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[a-zA-Z\\d]{8,16}$";
NSPredicate *passTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#",passRegex];
if ([passTest evaluateWithObject:pass] == YES)
{
_lbl2.text =#"";
}
else{
_lbl2.text =#"not valid";
}
}
if(textField ==_txt_email)
{
NSString *email =[_txt_email.text stringByReplacingCharactersInRange:range withString:string];
NSString *emailRegex = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,10}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegex];
if ([emailTest evaluateWithObject:email] == YES)
{
_lbl3.text =#"";
}
else{
_lbl3.text =#"not valid";
}
}
return YES;
}
- (IBAction)btt_save:(id)sender
{
if((_txt_user.text.length==0) || (_txt_pass.text.length==0) || (_txt_email.text.length==0))
{
UIAlertController *alert =[UIAlertController alertControllerWithTitle:#"title" message:#"please enter user,password,email" preferredStyle:UIAlertViewStyleDefault];
UIAlertAction* yesButton = [UIAlertAction
actionWithTitle:#"Yes, please"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
}];
UIAlertAction* cancelButton = [UIAlertAction
actionWithTitle:#"No, thanks"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
}];
[alert addAction:yesButton];
[alert addAction:cancelButton];
[self presentViewController:alert animated:yesButton completion:nil];
}
else
{
NSManagedObjectContext *context = [self managedObjectContext];
// Create a new managed object
NSManagedObject *details = [NSEntityDescription insertNewObjectForEntityForName:#"LogIn" inManagedObjectContext:context];
[details setValue:self.txt_user.text forKey:#"userName"];
[details setValue:self.txt_pass.text forKey:#"password"];
[details setValue:self.txt_email.text forKey:#"emailAddress"];
NSLog(#"12334%#",details);
NSError *error = nil;
_txt_user.text =#"";
_txt_pass.text =#"";
_txt_email.text =#"";
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# ",error .localizedDescription);
}
}
[self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)btt_cancel:(id)sender {
[self.navigationController popViewControllerAnimated:YES];
}
#end
#import "ViewController.h"
#import "secondTableViewCell.h"
#import "SecondViewController.h"
#interface ViewController ()<NSURLConnectionDelegate,NSURLConnectionDataDelegate,UITableViewDelegate,UITableViewDataSource>
#property(nonatomic,strong)NSData *get_data;
#property(nonatomic,strong)NSMutableArray *result_array;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *base_url = #"https://itunes.apple.com/lookup?id=909253&entity=album";
NSURL *url =[NSURL URLWithString:[NSString stringWithFormat:#"%#",base_url]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:url];
[request setHTTPMethod:#"GET"];
[NSURLConnection connectionWithRequest:request delegate:self];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark- nsurlconnection delegate
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
{
NSLog(#"%#",error.localizedDescription);
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(nonnull NSURLResponse *)response
{
NSLog(#"%#",response);
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(nonnull NSData *)data
{
NSLog(#"88888%#",data);
if ([data length])
{
self.get_data = [[NSData alloc]init];
self.get_data =data;
NSLog(#"%#",self.get_data);
}
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error = nil;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:self.get_data options:NSJSONReadingMutableLeaves error:&error];
NSLog(#"vijay%#",dict);
if (!error)
{
NSArray *array = [dict valueForKey:#"results"];
NSLog(#"1212%#",array);
self.result_array = [[NSMutableArray alloc]init];
self.result_array = [NSMutableArray arrayWithArray:array];
dispatch_async(dispatch_get_main_queue(), ^{
[_tableview reloadData];
});
}
}
#pragma mark -uitableview datasource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.result_array.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
secondTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"sri"];
if (cell == nil)
{
cell = [[secondTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
}
cell.lbl1.text = [[self.result_array valueForKey:#"wrapperType"]objectAtIndex:indexPath.row];
cell.lbl2.text = [[self.result_array valueForKey:#"artistName"]objectAtIndex:indexPath.row];
cell.lbl3.text = [[self.result_array valueForKey:#"primaryGenreName"]objectAtIndex:indexPath.row];
// integer to string
NSInteger artid = [[[self.result_array valueForKey:#"artistId"]objectAtIndex:indexPath.row] integerValue];
NSString *str = [NSString stringWithFormat:#"%ld",(long)artid];
// NSInteger release = [[[self.result_array valueForKey:#"releaseDate"]objectAtIndex:indexPath.row] integerValue];
//
// NSString *str1 = [NSString stringWithFormat:#"%ld",(long)release];
//
// cell.lbl3.text = str;
//// // // float to string
// float a = [[[self.result_array valueForKey:#"collectionPrice"]objectAtIndex:indexPath.row]floatValue];
// NSString *str1 = [NSString stringWithFormat:#"%.2f",a];
//
cell.lbl4.text = str;
////
//
cell.img1.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#",[[_result_array valueForKey:#"artworkUrl60"]objectAtIndex:indexPath.row]]]]];
//
//
//
//
//
//
return cell;
}
//
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self performSegueWithIdentifier:#"segue" sender:self];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"segue"]) {
//Do something
NSIndexPath *index = [self.tableview indexPathForSelectedRow];
SecondViewController *detailController = [segue destinationViewController];
// detailController.txt2= [cricket objectAtIndex:index.row];
detailController.imgg1= [UIImage imageNamed:[_result_array objectAtIndex:index.row]];
}
}
#end
#import "ViewController.h"
#import "CollectionViewCell1234.h"
#import "ViewController6778.h"
#interface ViewController ()<NSURLConnectionDelegate,NSURLConnectionDataDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UINavigationControllerDelegate>
#property (nonatomic ,strong)NSData *resultdata;
#property ( nonatomic,strong)NSMutableArray *array1;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self webserviceCallingUsingGETMethod];
_collectionview.backgroundColor = [UIColor purpleColor];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark- delegate
-(void)webserviceCallingUsingGETMethod
{
NSString *stringurl = #"https://itunes.apple.com/search?";
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#",stringurl]];
NSString *params = #"term=jack+johnson&entity=musicVideo";
NSData *postdata = [params dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postdata];
[NSURLConnection connectionWithRequest:request delegate:self];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
if (connectionError) {
NSLog(#"Error :%#", connectionError.localizedDescription);
return;
}
if (data) {
self.resultdata = data;
NSError *error = nil;
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:_resultdata options:NSJSONReadingAllowFragments error:&error];
NSLog(#"RESULT :%#", result);
NSArray *array = [result valueForKey:#"results"];
_array1 =[[NSMutableArray alloc]init];
_array1 = [NSMutableArray arrayWithArray:array];
NSLog(#"122345%#",array);
dispatch_async(dispatch_get_main_queue(), ^{
[_collectionview reloadData];
});
}
}];
}
#pragma mark-collectionview delegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return _array1.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
NSString *nschool = #"sri";
CollectionViewCell1234 *cell = [collectionView dequeueReusableCellWithReuseIdentifier:nschool forIndexPath:indexPath];
cell.imgview.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#",[[_array1 valueForKey:#"artworkUrl30"]objectAtIndex:indexPath.row]]]]];
cell.backgroundColor = [UIColor greenColor];
cell.lbl1.text = [[self.array1 valueForKey:#"wrapperType"]objectAtIndex:indexPath.row];
cell.lbl2.text = [[self.array1 valueForKey:#"artistName"]objectAtIndex:indexPath.row];
cell.lbl3.text = [[self.array1 valueForKey:#"releaseDate"]objectAtIndex:indexPath.row];
cell.lbl4.text = [[self.array1 valueForKey:#"country"]objectAtIndex:indexPath.row];
cell.lbl5.text = [[self.array1 valueForKey:#"currency"]objectAtIndex:indexPath.row];
cell.lbl6.text = [[self.array1 valueForKey:#"trackName"]objectAtIndex:indexPath.row];
cell.lbl7.text = [[self.array1 valueForKey:#"kind"]objectAtIndex:indexPath.row];
NSInteger artid= [[[self.array1 valueForKey:#"artistId"]objectAtIndex:indexPath.row]integerValue];
NSString *str1 =[NSString stringWithFormat:#"%ld",(long)artid];
cell.lbl8.text = str1;
CGFloat cp = [[[self.array1 valueForKey:#"collectionPrice"]objectAtIndex:indexPath.row]floatValue];
NSString *str4 = [NSString stringWithFormat:#"%3f",cp];
cell.lbl9.text = str4;
cell.lbl10.text = [[self.array1 valueForKey:#"collectionExplicitness"]objectAtIndex:indexPath.row];
cell.lbl11.text = [[self.array1 valueForKey:#"primaryGenreName"]objectAtIndex:indexPath.row];
NSInteger tracknum = [[[self.array1 valueForKey:#"trackId"]objectAtIndex:indexPath.row]integerValue];
NSString *str3 = [NSString stringWithFormat:#"%ld",(long)tracknum];
cell.lbl12.text = str3;
cell.lbl13.text = [[self.array1 valueForKey:#"trackExplicitness"]objectAtIndex:indexPath.row];
NSInteger tracknum1 =[[[self.array1 valueForKey:#"trackTimeMillis"]objectAtIndex:indexPath.row]integerValue];
NSString *str2 = [NSString stringWithFormat:#"%ld",(long)tracknum1];
cell.lbl14.text =str2;
return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
[self performSegueWithIdentifier:#"segue" sender:self];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"segue"])
{
ViewController6778 *vc2 = [segue destinationViewController];
vc2.img1.images ;
}
}
#end

getting error: expected ':' before '*' token in Xcode [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
i am trying to devlope one RSSFeed application from http://www.raywenderlich.com/2636/how-to-make-a-simple-rss-reader-iphone-app-tutorial. everything was going well till this error occurs. i have checked everything in tutorial code but couldn't find anything. i have copied the code as it is. i have stuck here & wanted to get rid off it so i can go further & work get done. i am putting the piece of code below. please anyone can help me with it.
thnx in advance..
// RootViewController.m
// RSSFun
#import "GDataXMLNode.h"
#import "GDataXMLElement-Extras.h"
#import "ASIHTTPRequest.h"
#import "RSSEntry.h"
#import "RootViewController.h"
#implementation RootViewController
#synthesize feeds = _feeds;
#synthesize queue = _queue;
#synthesize allEntries = _allEntries;
- (void)refresh {
for (NSString *feed in _feeds) {
NSURL *url = [NSURL URLWithString:feed];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[_queue addOperation:request];
}
}
- (void)addRows {
RSSEntry *entry1 = [[[RSSEntry alloc] initWithBlogTitle:#"1"
articleTitle:#"1"
articleUrl:#"1"
articleDate:[NSDate date]] autorelease];
RSSEntry *entry2 = [[[RSSEntry alloc] initWithBlogTitle:#"2"
articleTitle:#"2"
articleUrl:#"2"
articleDate:[NSDate date]] autorelease];
RSSEntry *entry3 = [[[RSSEntry alloc] initWithBlogTitle:#"3"
articleTitle:#"3"
articleUrl:#"3"
articleDate:[NSDate date]] autorelease];
[_allEntries insertObject:entry1 atIndex:0];
[_allEntries insertObject:entry2 atIndex:0];
[_allEntries insertObject:entry3 atIndex:0];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.title = #"Feeds";
self.allEntries = [NSMutableArray array];
self.queue = [[[NSOperationQueue alloc] init] autorelease];
self.feeds = [NSArray arrayWithObjects:#"http://feeds.feedburner.com/RayWenderlich",
#"http://feeds.feedburner.com/vmwstudios",
#"http://idtypealittlefaster.blogspot.com/feeds/posts/default",
#"http://www.71squared.com/feed/",
#"http://cocoawithlove.com/feeds/posts/default",
#"http://feeds2.feedburner.com/brandontreb",
#"http://feeds.feedburner.com/CoryWilesBlog",
#"http://geekanddad.wordpress.com/feed/",
#"http://iphonedevelopment.blogspot.com/feeds/posts/default",
#"http://karnakgames.com/wp/feed/",
#"http://kwigbo.com/rss",
#"http://shawnsbits.com/feed/",
#"http://pocketcyclone.com/feed/",
#"http://www.alexcurylo.com/blog/feed/",
#"http://feeds.feedburner.com/maniacdev",
#"http://feeds.feedburner.com/macindie",
nil];
[self refresh];
}
/*
- (void)viewDidLoad {
[super viewDidLoad];
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
*/
/*
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations.
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release anything that can be recreated in viewDidLoad or on demand.
// e.g. self.myOutlet = nil;
}
- (void)requestFinished:(ASIHTTPRequest *)request {
//Error occurs here
[_queue addOperationWithBlock:^
{
NSError *error;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[request responseData]
options:0 error:&error];
if (doc == nil) {
NSLog(#"Failed to parse %#", request.url);
} else {
NSMutableArray *entries = [NSMutableArray array];
[self parseFeed:doc.rootElement entries:entries];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
for (RSSEntry *entry in entries) {
int insertIdx = 0;
[_allEntries insertObject:entry atIndex:insertIdx];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:insertIdx inSection:0]]
withRowAnimation:UITableViewRowAnimationRight];
}
}];
}
}];
}
- (void)requestFailed:(ASIHTTPRequest *)request {
NSError *error = [request error];
NSLog(#"Error: %#", error);
}
- (void)parseFeed:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
if ([rootElement.name compare:#"rss"] == NSOrderedSame) {
[self parseRss:rootElement entries:entries];
} else if ([rootElement.name compare:#"feed"] == NSOrderedSame) {
[self parseAtom:rootElement entries:entries];
} else {
NSLog(#"Unsupported root element: %#", rootElement.name);
}
}
- (void)parseRss:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
NSArray *channels = [rootElement elementsForName:#"channel"];
for (GDataXMLElement *channel in channels) {
NSString *blogTitle = [channel valueForChild:#"title"];
NSArray *items = [channel elementsForName:#"item"];
for (GDataXMLElement *item in items) {
NSString *articleTitle = [item valueForChild:#"title"];
NSString *articleUrl = [item valueForChild:#"link"];
NSString *articleDateString = [item valueForChild:#"pubDate"];
NSDate *articleDate = nil;
RSSEntry *entry = [[[RSSEntry alloc] initWithBlogTitle:blogTitle
articleTitle:articleTitle
articleUrl:articleUrl
articleDate:articleDate] autorelease];
[entries addObject:entry];
}
}
}
- (void)parseAtom:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
NSString *blogTitle = [rootElement valueForChild:#"title"];
NSArray *items = [rootElement elementsForName:#"entry"];
for (GDataXMLElement *item in items) {
NSString *articleTitle = [item valueForChild:#"title"];
NSString *articleUrl = nil;
NSArray *links = [item elementsForName:#"link"];
for(GDataXMLElement *link in links) {
NSString *rel = [[link attributeForName:#"rel"] stringValue];
NSString *type = [[link attributeForName:#"type"] stringValue];
if ([rel compare:#"alternate"] == NSOrderedSame &&
[type compare:#"text/html"] == NSOrderedSame) {
articleUrl = [[link attributeForName:#"href"] stringValue];
}
}
NSString *articleDateString = [item valueForChild:#"updated"];
NSDate *articleDate = nil;
RSSEntry *entry = [[[RSSEntry alloc] initWithBlogTitle:blogTitle
articleTitle:articleTitle
articleUrl:articleUrl
articleDate:articleDate] autorelease];
[entries addObject:entry];
}
}
#pragma mark Table view methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [_allEntries count];
}
// 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];
}
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *articleDateString = [dateFormatter stringFromDate:entry.articleDate];
cell.textLabel.text = entry.articleTitle;
cell.detailTextLabel.text = [NSString stringWithFormat:#"%# - %#", articleDateString, entry.blogTitle];
return cell;
}
/*
// Override to support row selection in the table view.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic may go here -- for example, create and push another view controller.
// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:#"AnotherView" bundle:nil];
// [self.navigationController pushViewController:anotherViewController animated:YES];
// [anotherViewController release];
}
*/
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source.
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
*/
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
- (void)dealloc {
[super dealloc];
[_allEntries release];
_allEntries = nil;
[_queue release];
_queue = nil;
[_feeds release];
_feeds = nil;
}
#end
Just before your dealloc method you have a spurious */ which needs removing.
enter code hereRight at teh end of your file you have the following:
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
That last end comment block */ should be removed as it has no start block. leaving:
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the item to be re-orderable.
return YES;
}

Objective-C woes: cellForRowAtIndexPath crashes

I want to the user to be able to search for a record in a DB. The fetch and the results returned work perfectly. I am having a hard time setting the UItableview to display the result tho. The application continually crashes at cellForRowAtIndexPath. Please, someone help before I have a heart attack over here. Thank you.
#implementation SearchViewController
#synthesize mySearchBar;
#synthesize textToSearchFor;
#synthesize myGlobalSearchObject;
#synthesize results;
#synthesize tableView;
#synthesize tempString;
#pragma mark -
#pragma mark View lifecycle
- (void)viewDidLoad {
[super viewDidLoad];
}
#pragma mark -
#pragma mark Table View
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//handle selection; push view
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
/* if(nullResulSearch == TRUE){
return 1;
}else {
return[results count];
}
*/
return[results count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 1; // Test hack to display multiple rows.
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Search Cell Identifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil){
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:CellIdentifier] autorelease];
}
NSLog(#"TEMPSTRING %#", tempString);
cell.textLabel.text = tempString;
return cell;
}
#pragma mark -
#pragma mark Memory management
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload {
self.tableView = nil;
}
- (void)dealloc {
[results release];
[mySearchBar release];
[textToSearchFor release];
[myGlobalSearchObject release];
[super dealloc];
}
#pragma mark -
#pragma mark Search Function & Fetch Controller
- (NSManagedObject *)SearchDatabaseForText:(NSString *)passdTextToSearchFor{
NSManagedObject *searchObj;
UndergroundBaseballAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *managedObjectContext = appDelegate.managedObjectContext;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"name == [c]%#", passdTextToSearchFor];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Entry" inManagedObjectContext:managedObjectContext];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[request setEntity: entity];
[request setPredicate: predicate];
NSError *error;
results = [managedObjectContext executeFetchRequest:request error:&error];
if([results count] == 0){
NSLog(#"No results found");
searchObj = nil;
nullResulSearch == TRUE;
}else{
if ([[[results objectAtIndex:0] name] caseInsensitiveCompare:passdTextToSearchFor] == 0) {
NSLog(#"results %#", [[results objectAtIndex:0] name]);
searchObj = [results objectAtIndex:0];
nullResulSearch == FALSE;
}else{
NSLog(#"No results found");
searchObj = nil;
nullResulSearch == TRUE;
}
}
[tableView reloadData];
[request release];
[sortDescriptors release];
return searchObj;
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
textToSearchFor = mySearchBar.text;
NSLog(#"textToSearchFor: %#", textToSearchFor);
myGlobalSearchObject = [self SearchDatabaseForText:textToSearchFor];
NSLog(#"myGlobalSearchObject: %#", myGlobalSearchObject);
tempString = [myGlobalSearchObject valueForKey:#"name"];
NSLog(#"tempString: %#", tempString);
}
#end
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[UILongPressGestureRecognizer isEqualToString:]: unrecognized selector sent to instance 0x3d46c20'
The problem may be to do with reference counting.
in - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar method, try either
self.tempString = [myGlobalSearchObject valueForKey:#"name"];
(assuming tempString is set to retain)
OR
tempString = [[myGlobalSearchObject valueForKey:#"name"] retain];
I would also advise doing some checking for nil values. i.e. what if [myGlobalSearchObject valueForKey:#"name"] == nil?