Objective-C woes: cellForRowAtIndexPath crashes - iphone

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?

Related

table cell showing up in wrong section in table view

DataModel.h code file
#import "DataModel.h"
#import <CoreData/CoreData.h>
#import "SettingsEntity.h"
#import "Constants.h"
#implementation DataModel
NSManagedObjectContext *managedObjectContextEntity;
NSManagedObjectContext *managedObjectContextMessage;
NSManagedObjectModel *managedObjectModel;
NSPersistentStoreCoordinator *persistentStoreCoordinator;
NSEntityDescription *theSettingsEntity;
NSEntityDescription *theMessagesEntity;
-(id) init
{
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"SOW" withExtension:#"momd"];
managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
NSError *error = nil;
NSURL *storeURL = [[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] URLByAppendingPathComponent:[Constants SQLLiteDB]];
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:managedObjectModel];
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
if (persistentStoreCoordinator != nil) {
managedObjectContextEntity = [[NSManagedObjectContext alloc] init];
[managedObjectContextEntity setPersistentStoreCoordinator:persistentStoreCoordinator];
managedObjectContextMessage = [[NSManagedObjectContext alloc] init];
[managedObjectContextMessage setPersistentStoreCoordinator:persistentStoreCoordinator];
}
theSettingsEntity = [NSEntityDescription entityForName:#"SettingsEntity" inManagedObjectContext:managedObjectContextEntity];
theMessagesEntity = [NSEntityDescription entityForName:#"MessageEntity" inManagedObjectContext:managedObjectContextMessage];
return self;
}
-(void) SaveSetting: (SettingsEntity *)setting
{
NSError *error = nil;
if (managedObjectContextEntity != nil) {
if ([managedObjectContextEntity hasChanges] && ![managedObjectContextEntity save:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Confirmation" message:#"Settings were saved successfully." delegate:nil cancelButtonTitle:#"Okay" otherButtonTitles:nil, nil];
[alert show];
}
}
}
-(void) SaveMessage: (MessageEntity *)message
{
NSError *error = nil;
if (managedObjectContextMessage != nil) {
if ([managedObjectContextMessage hasChanges] && ![managedObjectContextMessage save:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
}
-(NSArray *) GetSettingsResult
{
NSManagedObjectContext *context = managedObjectContextEntity;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:theSettingsEntity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"enteredDateTime" ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
NSArray *results = [context executeFetchRequest:request error:nil];
return results;
}
-(SettingsEntity *) GetSettingsEntity
{
SettingsEntity *settingsEntity = [NSEntityDescription
insertNewObjectForEntityForName:[theSettingsEntity name]
inManagedObjectContext:managedObjectContextEntity];
return settingsEntity;
}
-(NSArray *) GetMessageResult
{
NSFetchRequest *request = [self GetMessageFetchRequest];
NSArray *results = [managedObjectContextMessage executeFetchRequest:request error:nil];
return results;
}
-(NSFetchRequest *) GetMessageFetchRequest
{
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:theMessagesEntity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"sentDateTime" ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
return request;
}
-(NSFetchedResultsController *) GetMessageFetchResultsController
{
NSFetchRequest *fetchRequest = [self GetMessageFetchRequest];
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContextMessage sectionNameKeyPath:#"typeMessage" cacheName:nil];
return aFetchedResultsController;
}
-(MessageEntity *) GetMessageEntity
{
MessageEntity *mEntity = [NSEntityDescription
insertNewObjectForEntityForName:[theMessagesEntity name]
inManagedObjectContext:managedObjectContextMessage];
return mEntity;
}
#end
HistoryTableView code file is as follows:
#import "HistoryTableViewController.h"
#import "MessageEntity.h"
#import "DataModel.h"
#import "HistoryDetailViewController.h"
#import "Constants.h"
#interface HistoryTableViewController ()
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath;
#end
#implementation HistoryTableViewController
//todo: zulfiqar review this line of code.
#synthesize fetchedResultsController = __fetchedResultsController;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)awakeFromNib
{
[super awakeFromNib];
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.rightBarButtonItem = self.editButtonItem;
//todo: get fetched controller here.. and reuse it every where in rest of this class.
}
/* faisal code starts here */
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSFetchedResultsController *c = [self fetchedResultsController];
NSArray *titles = [c sectionIndexTitles];
NSString *title = titles[section];
if ([title isEqualToString:#"E"])
{
return [Constants Email];
}
else if([title isEqualToString:#"T"])
{
return [Constants Text];
}
else
{
return [Constants Call];
}
}
- (NSArray *)sectionIndexTitlesForTableView: (UITableView *)aTableView
{
NSFetchedResultsController *c = [self fetchedResultsController];
return [c sectionIndexTitles];
}
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSFetchedResultsController *c = [self fetchedResultsController];
id<NSFetchedResultsSectionInfo> sectionInfo = c.sections[section];
return sectionInfo.numberOfObjects;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSFetchedResultsController *c = [self fetchedResultsController];
return c.sections.count;
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
NSIndexPath *path = self.tableView.indexPathForSelectedRow;
HistoryDetailViewController *hdvc = segue.destinationViewController;
NSFetchedResultsController *c = [self fetchedResultsController];
MessageEntity *message = (MessageEntity *)[c objectAtIndexPath:path];
hdvc.currentMessageEntity = message;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
/*
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSFetchedResultsController *c = [self fetchedResultsController];
id <NSFetchedResultsSectionInfo> sectionInfo = c.sections[section];
return sectionInfo.numberOfObjects;
}
*/
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSFetchedResultsController *c = [self fetchedResultsController];
NSString *CellIdentifier = [NSString stringWithFormat:#"Cell"];// %d_%d",indexPath.section,indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
MessageEntity *message = (MessageEntity *)[c objectAtIndexPath:indexPath];
cell.textLabel.text = message.typeMessage;
return cell;
/*
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"EEE. MMM. dd, yyyy HH:mm"];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
NSFetchedResultsController *c = [self fetchedResultsController];
MessageEntity *message = (MessageEntity *)[c objectAtIndexPath:indexPath];
NSString *sentDateTime = [dateFormat stringFromDate:message.sentDateTime];
NSString *contactAdd;
NSLog(message.typeMessage);
if ([message.typeMessage isEqualToString:[Constants Email]])
{
contactAdd = message.toEmailAddress;
}
else
{
NSString *unformatted = message.toPhoneNumber;
NSArray *stringComponents = [NSArray arrayWithObjects:[unformatted substringWithRange:NSMakeRange(0, 3)],
[unformatted substringWithRange:NSMakeRange(3, 3)],
[unformatted substringWithRange:NSMakeRange(6, [unformatted length]-6)], nil];
contactAdd = [NSString stringWithFormat:#"(%#) %#-%#", [stringComponents objectAtIndex:0], [stringComponents objectAtIndex:1], [stringComponents objectAtIndex:2]];
}
NSString *header = [[NSString alloc] initWithFormat:#"%#",contactAdd];
NSString *detail = [[NSString alloc] initWithFormat:#"%# on %#", message.sentName, sentDateTime];
cell.detailTextLabel.text = detail;
cell.textLabel.text = header;
return cell;
*/
}
// 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;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
NSFetchedResultsController *c = [self fetchedResultsController];
NSManagedObject *object = [c objectAtIndexPath:indexPath];
NSManagedObjectContext *context = self.fetchedResultsController.managedObjectContext;
[context deleteObject:object];
NSError *error = nil;
if (![context save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
// The table view should not be re-orderable.
return NO;
}
- (void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView reloadData];
}
- (NSFetchedResultsController *)fetchedResultsController
{
if (__fetchedResultsController != nil) {
return __fetchedResultsController;
}
DataModel *data = [[DataModel alloc]init];
NSFetchedResultsController *aFetchedResultsController = [data GetMessageFetchResultsController];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return __fetchedResultsController;
}
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
[self.tableView beginUpdates];
}
- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
{
switch(type) {
case NSFetchedResultsChangeDelete:
[self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath
{
UITableView *tableView = self.tableView;
switch(type) {
case NSFetchedResultsChangeDelete:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
[self.tableView endUpdates];
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
/*
<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:#"<#Nib name#>" bundle:nil];
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
*/
}
#end
My history table view looks as follows:
**Q. Why Email and Call are getting into wrong section?**
If you set a sectionNameKeyPath for the fetched results controller, then you must also add a first sort descriptor to the fetch request that uses the same key (or a key that generates the same relative ordering).
So for sectionNameKeyPath:#"typeMessage" you should add one sort descriptor for the key "typeMessage":
NSSortDescriptor *sort1 = [[NSSortDescriptor alloc] initWithKey:#"typeMessage" ascending:YES];
NSSortDescriptor *sort2 = [[NSSortDescriptor alloc] initWithKey:#"sentDateTime" ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sort1, sort2, nil];
[request setSortDescriptors:sortDescriptors];

Use of undeclared identifier - Core Data

Hi i'm fairly new to xcode and i'm having trouble getting my head around why im getting this error "use of undeclared identifier" I'm basically trying to return fetched results to a table view.
// UNBSearchBooksViewController.m
#import "UNBSearchBooksViewController.h"
#import "NBAppDelegate.h"
#interface UNBSearchBooksViewController ()
#end
#implementation UNBSearchBooksViewController
#synthesize booksSearchBar;
#synthesize searchTableView;
#synthesize fetchedResultsController, managedObjectContext;
- (void)viewDidLoad
{
[super viewDidLoad];
// NSFetchRequest needed by the fetchedResultsController
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// NSSortDescriptor tells defines how to sort the fetched results
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"title" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
// fetchRequest needs to know what entity to fetch
NSEntityDescription *entity = [NSEntityDescription entityForName:#"BookInfo" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:#"Root"];
}
- (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 [fetchedObjects 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:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell "this is where my problem is" use of undeclared identifier
BookInfo *info = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = info.title;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
- (void) searchBarSearchButtonClicked:(UISearchBar *)theSearchBar
{
if (self.booksSearchBar.text !=nil)
{
NSPredicate *predicate =[NSPredicate predicateWithFormat:#"bookName contains[cd] %#", self.booksSearchBar.text];
[fetchedResultsController.fetchRequest setPredicate:predicate];
}
else
{
NSPredicate *predicate =[NSPredicate predicateWithFormat:#"All"];
[fetchedResultsController.fetchRequest setPredicate:predicate];
}
NSError *error = nil;
if (![[self fetchedResultsController] performFetch:&error])
{
// Handle error
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
exit(-1); // Fail
}
fetchedObjects = fetchedResultsController.fetchedObjects;
[booksSearchBar resignFirstResponder];
[searchTableView reloadData];
}
- (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
searchBar.showsCancelButton = YES;
}
- (void) searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
searchBar.showsCancelButton = NO;
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
[searchBar resignFirstResponder];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
#end
Your problem is that you are assigning to a specific subclass the results typed as a base class. As you stated, this is where you get the warning:
BookInfo *info = [self.fetchedResultsController objectAtIndexPath:indexPath];
'NSFetchedResultsController' returns an object of type 'id' from
- (id)objectAtIndexPath:(NSIndexPath *)indexPath
(and I suppose it could return a NSManagedObject * too), but you assign it to a BookInfo object. Since there is a mismatch here, you need to cast the return value to what you know it is:
BookInfo *info = (BookInfo *)[self.fetchedResultsController objectAtIndexPath:indexPath];
and your warning will go away.

Uncaught exception error! Simple document app

Removed the colon which wasn't supposed to be there since my selector doesn't have one. It fixed it, then this problem occurred:
2012-06-02 22:33:10.083 TinyPix[10433:fb03] load OK
2012-06-02 22:33:10.084 TinyPix[10433:fb03] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<BIDTinyPixDocument 0x6e665a0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key timeStamp.'
*** First throw call stack:
(0x16b0022 0x1841cd6 0x16afee1 0x9c8efe 0x937831 0x936c99 0x5f47 0x5e77 0x93af30 0x93aedb 0x59ed 0x4546e3 0x40778d9 0x4078509 0x15e7803 0x15e6d84 0x15e6c9b 0x15997d8 0x159988a 0x1b626 0x2a5d 0x29c5)
terminate called throwing an exception
Here's my detail file: I'm getting a SIGABRT error on the self.detailDescriptionLabel.text line. Don't know what's going on.
#import "BIDDetailViewController.h"
#interface BIDDetailViewController ()
- (void)configureView;
#end
#implementation BIDDetailViewController
#synthesize detailItem = _detailItem;
#synthesize detailDescriptionLabel = _detailDescriptionLabel;
#pragma mark - Managing the detail item
- (void)setDetailItem:(id)newDetailItem
{
if (_detailItem != newDetailItem) {
_detailItem = newDetailItem;
// Update the view.
[self configureView];
}
}
- (void)configureView
{
// Update the user interface for the detail item.
if (self.detailItem) {
self.detailDescriptionLabel.text = [[self.detailItem valueForKey:#"timeStamp"] description];
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self configureView];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
self.detailDescriptionLabel = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#end
Here's my file:
#import "BIDMasterViewController.h"
#import "BIDTinyPixDocument.h"
#import "BIDDetailViewController.h"
#interface BIDMasterViewController () <UIAlertViewDelegate>
#property (strong, nonatomic) NSArray *documentFilenames;
#property (strong, nonatomic) BIDTinyPixDocument *chosenDocument;
-(NSURL *)urlForFilename:(NSString *)filename;
-(void)reloadFiles;
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath;
#end
#implementation BIDMasterViewController
#synthesize colorControl;
#synthesize documentFilenames;
#synthesize chosenDocument;
#synthesize fetchedResultsController = __fetchedResultsController;
#synthesize managedObjectContext = __managedObjectContext;
- (void)awakeFromNib
{
[super awakeFromNib];
}
-(void)viewWillAppear:(BOOL)animated;
{
[super viewWillAppear:animated];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSInteger selectedColorIndex = [prefs integerForKey:#"selectedColorIndex"];
self.colorControl.selectedSegmentIndex = selectedColorIndex;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem;
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(insertNewObject:)];
self.navigationItem.rightBarButtonItem = addButton;
[self reloadFiles];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (void)insertNewObject
{
// get the name
UIAlertView *alert =
[[UIAlertView alloc] initWithTitle:#"Filename"
message:#"Enter a name for your new TinyPix document."
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Create", nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[alert show];
}
#pragma mark - Table View
- (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
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
[context deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]];
NSError *error = nil;
if (![context save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
// The table view should not be re-orderable.
return NO;
}
#pragma mark - Fetched results controller
- (NSFetchedResultsController *)fetchedResultsController
{
if (__fetchedResultsController != nil) {
return __fetchedResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Event" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
// Set the batch size to a suitable number.
[fetchRequest setFetchBatchSize:20];
// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"timeStamp" ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:#"Master"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return __fetchedResultsController;
}
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
[self.tableView beginUpdates];
}
- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
{
switch(type) {
case NSFetchedResultsChangeInsert:
[self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath
{
UITableView *tableView = self.tableView;
switch(type) {
case NSFetchedResultsChangeInsert:
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeUpdate:
[self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
break;
case NSFetchedResultsChangeMove:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
[self.tableView endUpdates];
}
/*
// Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed.
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
// In the simplest, most efficient, case, reload the table view.
[self.tableView reloadData];
}
*/
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
NSManagedObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = [[object valueForKey:#"timeStamp"] description];
}
-(NSURL *)urlForFilename:(NSString *)filename {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentDirectory stringByAppendingPathComponent:filename];
NSURL *url = [NSURL fileURLWithPath:filePath];
return url;
}
-(void)reloadFiles {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSFileManager *fm = [NSFileManager defaultManager];
NSError *dirError;
NSArray *files = [fm contentsOfDirectoryAtPath:path error:&dirError];
if (!files) {
NSLog(#"Encountered error while trying to list files in directory %#: %#", path, dirError);
}
NSLog(#"found files: %#", files);
files = [files sortedArrayUsingComparator:^NSComparisonResult(id filename1, id filename2) {
NSDictionary *attr1 = [fm attributesOfItemAtPath:[path stringByAppendingPathComponent:filename1]
error:nil];
NSDictionary *attr2 = [fm attributesOfItemAtPath:[path stringByAppendingPathComponent:filename2]
error:nil];
return [[attr2 objectForKey:NSFileCreationDate] compare:[attr1 objectForKey:NSFileCreationDate]];
}];
self.documentFilenames = files;
[self.tableView reloadData];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.documentFilenames count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"FileCell"];
NSString *path = [self.documentFilenames objectAtIndex:indexPath.row];
cell.textLabel.text = path.lastPathComponent.stringByDeletingPathExtension;
return cell;
}
-(IBAction)chooseColor:(id)sender {
NSInteger selectedColorIndex = [(UISegmentedControl *)sender selectedSegmentIndex];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setInteger:selectedColorIndex forKey:#"selectedColorIndex"];
}
-(void)alertView:(UIAlertView *)alertView
didDismissWithButtonIndex:(NSInteger)buttonIndex {
if (buttonIndex == 1) {
NSString *filename = [NSString stringWithFormat:#"%#.tinypix",
[alertView textFieldAtIndex:0].text];
NSURL *saveUrl = [self urlForFilename:filename];
self.chosenDocument = [[BIDTinyPixDocument alloc] initWithFileURL:saveUrl];
[chosenDocument saveToURL:saveUrl
forSaveOperation:UIDocumentSaveForCreating
completionHandler:^(BOOL success) {
if (success) {
NSLog(#"save OK");
[self reloadFiles];
[self performSegueWithIdentifier:#"masterToDetail"
sender:self];
} else {
NSLog(#"failed to save!");
}
}];
}
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if (sender == self) {
// if sender == self, a new document has just been created,
// and chosenDocument is already set.
UIViewController *destination = segue.destinationViewController;
if ([destination respondsToSelector:#selector(setDetailItem:)]) {
[destination setValue:self.chosenDocument forKey:#"detailItem"];
}
}else {
// find the chose document from the tableview
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
NSString *filename = [documentFilenames objectAtIndex:indexPath.row];
NSURL *docUrl = [self urlForFilename:filename];
self.chosenDocument = [[BIDTinyPixDocument alloc] initWithFileURL:docUrl];
[self.chosenDocument openWithCompletionHandler:^(BOOL success) {
if (success) {
NSLog(#"load OK");
UIViewController *destination = segue.destinationViewController;
if ([destination respondsToSelector:#selector(setDetailItem:)]) {
[destination setValue:self.chosenDocument forKey:#"detailItem"];
}
}else {
NSLog(#"failed to load!");
}
}];
}
}
#end
You specify the selector as insertNewObject: and the colon on the end says that it takes one parameter. The insertNewObject method you implemented takes no parameters and, to Objective-C, that makes it a different thing and it can't find the one parameter method.
You should change your implementation to - (IBAction)insertNewObject:(id)sender {...} to match #selector(insertNewObject:).

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

CoreData leaks when view is destroyed

I'm trying to finish an app but I'm having some memory leaks with CoreData when I delete the view from the navigation stack even though I released everything I created.
Basically the following method is called by the view below it.
+ (NSMutableArray *)getStoriesForSubscription:(Subscriptions *)s {
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *storiesEntity = [NSEntityDescription entityForName:#"Articles" inManagedObjectContext:ikub.context];
[request setEntity:storiesEntity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"(belongsTo == %#)", s];
[request setPredicate:predicate];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"pubDate" ascending:NO selector:nil];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
NSError *error = nil;
NSMutableArray *stories = (NSMutableArray*)[ikub.context executeFetchRequest:request error:&error];
if (![ikub.context save:&error]) { NSLog(#"Cannot fetch the folders from the fetch request."); }
[sortDescriptors release];
[sortDescriptor release];
[request release];
return stories;
}
#implementation SubscriptionStories
#synthesize storiesTable, stories, subscription;
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [stories count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"cell"];
}
int index = [indexPath row];
cell.textLabel.text = [[stories objectAtIndex:index] title];
cell.detailTextLabel.text = [[stories objectAtIndex:index] desc];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
if ([[[stories objectAtIndex:index] read] isEqualToNumber:[NSNumber numberWithBool:NO]]) {
cell.textLabel.textColor = [UIColor blackColor];
} else {
cell.textLabel.textColor = [UIColor grayColor];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
StoryDetails *details = [[StoryDetails alloc] init];
details.title = #"Detaje";
details.t = [[stories objectAtIndex:[indexPath row]] title];
details.d = [[stories objectAtIndex:[indexPath row]] desc];
details.l = [[stories objectAtIndex:[indexPath row]] link];
details.g = [[stories objectAtIndex:[indexPath row]] guid];
details.p = (NSString *)[[stories objectAtIndex:[indexPath row]] pubDate];
[SubscriptionsController setStoryAsRead:[[stories objectAtIndex:[indexPath row]] link] forSubscription:subscription];
[self.navigationController pushViewController:details animated:YES];
[details release];
}
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)viewWillAppear:(BOOL)animated {
stories = [[SubscriptionsController getStoriesForSubscription:subscription] retain];
[storiesTable reloadData];
}
- (void)viewWillDisappear:(BOOL)animated {
[stories release];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload {
[super viewDidUnload];
}
- (void)dealloc {
[subscription release];
[super dealloc];
}
Instruments says that the leak happens in this line:
stories = [[SubscriptionsController getStoriesForSubscription:subscription] retain];
If you have declared the property stories with retain then the extra retain is not necessary.
self.stories = [SubscriptionsController getStoriesForSubscription:subscription];
my suggestions:
remove (another?) leak by changing your UITableViewCell creation to return an autoreleased cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
...
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"cell"] autorelease];
...
}
if that didn't help. (I had leaks were instruments was miles away from the actual leak). change your viewWillDisappear method to something like this
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[stories release];
stories = nil;
}
and add another release for stories in dealloc
- (void)dealloc {
[subscription release];
[stories release];
[super dealloc];
}
Maybe there are obscure ways that a dealloc happens without calling the viewWillDisappear: method.
I usually release everything in dealloc. As long as you make sure that you set an object to nil when you have released it in another method nothing bad will happen.
The leak was in a totally different place. Instruments isn't always right.