Array is deleting the last object in Xcode - objective-c

Here is my main view controller. I am populating a custom calendar with events from an xml file. This is working fine... Im also adding my own events. I use the same array for both. It appears that when I add a new event to the array. It deletes the previous one.
#import "CalendarViewController.h"
#import "HeaderCollectionReusableView.h"
#import "CalendarCollectionViewCell.h"
#import "EventViewController.h"
#import "AppDelegate.h"
#import "events.h"
#import "AddViewController.h"
#interface CalendarViewController ()
#end
#implementation CalendarViewController
UIImageView *navBarHairlineImageView;
BOOL _viewDidLayoutSubviewsForTheFirstTime = YES;
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#"VIEW DID LOAD");
// Do any additional setup after loading the view.
self.title = #"Calendar";
//\n in xml is encoded as
_viewDidLayoutSubviewsForTheFirstTime = YES;
if (!_calendar) {
[self setCalendar:[NSCalendar currentCalendar]];
}
_date = [[NSDate alloc] init];
NSDateComponents *components = [_calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:_date];
// set calendar from 2000 to current year + 10 years range
long year = components.year;
long month = components.month;
long day = components.day;
// NSLog(#"%ld %ld %ld", day, month, year);
_initialSection = (year - 2000) * 12 + month - 1; // index sections start at 0
components.day = 1;
components.month = 1;
components.year = 2000;
_firstDate = [_calendar dateFromComponents:components];
components.year = year + 10;
components.day = -1;
_lastDate = [_calendar dateFromComponents:components];
UINavigationBar *navigationBar = self.navigationController.navigationBar;
navBarHairlineImageView = [self findHairlineImageViewUnder:navigationBar];
UIView *bottomBorder = [[UIView alloc] init];
bottomBorder.backgroundColor = [UIColor lightGrayColor];
bottomBorder.frame = CGRectMake(0, _days.frame.size.height - 0.5, _days.frame.size.width, 0.5);
[_days addSubview:bottomBorder];
AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
NSData *data = appDelegate.data;
NSString *a = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSString *b = [a stringByReplacingOccurrencesOfString:#"
" withString:#"\n"];
data = [b dataUsingEncoding:NSUTF8StringEncoding];
//NSLog(#"%#", b);
_eventParser = [[NSXMLParser alloc] initWithData:data];
_eventsA = [[NSMutableArray alloc] init];
[_eventParser setDelegate:self];
[_eventParser parse];
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = dirPaths[0];
_databasesPath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent:#"ev.db"]];
// NSFileManager *filemgr = [NSFileManager defaultManager];
const char *dbpaths = [_databasesPath UTF8String];
sqlite3_stmt *statement;
if(sqlite3_open(dbpaths, &_myDB) == SQLITE_OK){
NSString *querySQL = #"SELECT * FROM event";
const char *query_stmt = [querySQL UTF8String];
NSLog(#"I SEE YOUFIRST");
if(sqlite3_prepare_v2(_myDB, query_stmt, -1, &statement, NULL) == SQLITE_OK){
// const char *query_stmt = [querySQL UTF8String];
//query_stmt = [querySQL UTF8String];
// NSMutableArray *allMessages = [[NSMutableArray alloc] init];
NSLog(#"I SEE YOU");
if(sqlite3_prepare_v2(_myDB, query_stmt, -1, &statement, NULL) == SQLITE_OK){
while(sqlite3_step(statement) == SQLITE_ROW){
NSString *typeField = [[NSString alloc] initWithUTF8String:(const char * ) sqlite3_column_text(statement, 0)];
NSString *descriptionField = [[NSString alloc] initWithUTF8String:(const char * ) sqlite3_column_text(statement, 1)];
NSString *dateField = [[NSString alloc] initWithUTF8String:(const char * ) sqlite3_column_text(statement, 2)];
// NSLog(#"%#", dateField);
// NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: typeField, #"typeField", descriptionField, #"descriptionField", dateField, #"dateField", nil];
// [allMessages addObject:dict];
_currentevent.eventType = typeField; //[dict objectForKey:#"typeField"];
_currentevent.eventDate = dateField; //[dict objectForKey:#"dateField"];
_currentevent.eventDescription = descriptionField; //[dict objectForKey:#"descriptionField"];
if (![_eventsA containsObject:_currentevent]){
[self.eventsA addObject:_currentevent];
}
// NSLog(#"Type: %# Description:%# Date:%#" , typeField, descriptionField, dateField );
//[_eventsA addObject:dateField];
// [_eventsA addObject:nameField];
//[_eventsA addObject:typeField];
}
sqlite3_finalize(statement);
}
sqlite3_close(_myDB);
}
}
else {
NSLog (#"Failed to add event");
}
NSLog(#"%lu" , (unsigned long)[_eventsA count]);
for(int i = 0; i < [_eventsA count]; i++) {
events *ex = [_eventsA objectAtIndex:i];
NSString *ds = ex.eventDate;
NSString *dd = ex.eventDescription;
NSLog(#"%# %#", ds, dd);
}
}
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
// Only scroll when the view is rendered for the first time
if (_viewDidLayoutSubviewsForTheFirstTime) {
_viewDidLayoutSubviewsForTheFirstTime = NO;
UICollectionViewLayoutAttributes *attributes = [_calendarCollectionView layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:_initialSection]];
CGRect rect = attributes.frame;
[_calendarCollectionView setContentOffset:CGPointMake(_calendarCollectionView.frame.origin.x, rect.origin.y - 32) animated:NO];
}
}
// find and remove hairline image under top bar
- (UIImageView *)findHairlineImageViewUnder:(UIView *)view {
if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0) {
return (UIImageView *)view;
}
for (UIView *subview in view.subviews) {
UIImageView *imageView = [self findHairlineImageViewUnder:subview];
if (imageView) {
return imageView;
}
}
return nil;
}
-(void)viewWillAppear:(BOOL)animated {
navBarHairlineImageView.hidden = YES;
[self viewDidLoad];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
navBarHairlineImageView.hidden = NO;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//#pragma mark -
#pragma mark UICollectionViewDataSource
-(NSInteger)numberOfSectionsInCollectionView:
(UICollectionView *)collectionView
{
return [_calendar components:NSCalendarUnitMonth fromDate:_firstDate toDate:_lastDate options:0].month + 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView
numberOfItemsInSection:(NSInteger)section
{
NSDate *firstOfMonth = [self firstOfMonthForSection:section];
NSRange rangeOfWeeks = [_calendar rangeOfUnit:NSCalendarUnitWeekOfMonth inUnit:NSCalendarUnitMonth forDate:firstOfMonth];
//We need the number of calendar weeks for the full months (it will maybe include previous month and next months cells)
int daysPerWeek = 7;
return (rangeOfWeeks.length * daysPerWeek);
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CalendarCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"calendarCell" forIndexPath:indexPath];
NSDate *firstOfMonth = [self firstOfMonthForSection:indexPath.section];
NSDate *cellDate = [self dateForCellAtIndexPath:indexPath];
NSDateComponents *cellDateComponents = [_calendar components:NSCalendarUnitDay|NSCalendarUnitMonth|NSCalendarUnitYear fromDate:cellDate];
NSDateComponents *firstOfMonthsComponents = [_calendar components:NSCalendarUnitMonth fromDate:firstOfMonth];
NSDateComponents *todayComponents = [_calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:[NSDate date]];
if(cellDateComponents.month == firstOfMonthsComponents.month) {
NSString *day = #"";
NSDateFormatter *dateFormatter;
dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"d";
day = [dateFormatter stringFromDate:cellDate];
cell.dateNumber.text = day;
cell.dateNumber.layer.cornerRadius = 7.0;
cell.dateNumber.clipsToBounds = YES;
if(cellDateComponents.day == todayComponents.day &&
cellDateComponents.month == todayComponents.month &&
cellDateComponents.year == todayComponents.year) {
cell.dateNumber.backgroundColor = [UIColor redColor];
cell.dateNumber.textColor = [UIColor whiteColor];
}
else {
cell.dateNumber.backgroundColor = [UIColor clearColor];
cell.dateNumber.textColor = [UIColor blackColor];
if(indexPath.row % 7 == 0 || (indexPath.row + 1) % 7 == 0)
cell.dateNumber.textColor = [UIColor lightGrayColor];
else
cell.dateNumber.textColor = [UIColor blackColor];
}
cell.event.layer.cornerRadius = 3.0;
cell.event.clipsToBounds = YES;
NSDateFormatter *eventFormatter = [[NSDateFormatter alloc] init];
eventFormatter.dateFormat = #"yyyy-MM-dd";
NSString *dateCell = [eventFormatter stringFromDate:cellDate];
NSString *markedEvent = #"";
for(int i = 0; i < [_eventsA count]; i++) {
events *temp = [_eventsA objectAtIndex:i];
markedEvent = temp.eventDate;
if([markedEvent isEqualToString:dateCell]) {
cell.event.backgroundColor = [UIColor lightGrayColor];
cell.hasEvent = YES;
}
}
}
else {
cell.dateNumber.text = #"";
}
cell.layer.shouldRasterize = YES;
cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
return cell;
}
#pragma mark - UICollectionViewDelegate
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
NSDate *firstOfMonth = [self firstOfMonthForSection:indexPath.section];
NSDate *cellDate = [self dateForCellAtIndexPath:indexPath];
//We don't want to select Dates that are "disabled"
if (![self isEnabledDate:cellDate]) {
return NO;
}
NSDateComponents *cellDateComponents = [_calendar components:NSCalendarUnitDay|NSCalendarUnitMonth fromDate:cellDate];
NSDateComponents *firstOfMonthsComponents = [_calendar components:NSCalendarUnitMonth fromDate:firstOfMonth];
return (cellDateComponents.month == firstOfMonthsComponents.month);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
CalendarCollectionViewCell *cell = (CalendarCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
cell.dateNumber.layer.cornerRadius = 7.0;
cell.dateNumber.clipsToBounds = YES;
cell.dateNumber.backgroundColor = [UIColor grayColor];
cell.dateNumber.textColor = [UIColor whiteColor];
_selectedDate = [self dateForCellAtIndexPath:indexPath];
if(cell.hasEvent) {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"EEEE MMMM d, yyyy";
NSDate *cellDate = [self dateForCellAtIndexPath:indexPath];
NSString *stringDate = [formatter stringFromDate:cellDate];
NSString *stringType;
NSString *stringDescription;
NSString *tempDate;
NSDateFormatter *fm = [[NSDateFormatter alloc] init];
fm.dateFormat = #"yyyy-MM-dd";
NSString *cd = [fm stringFromDate:cellDate];
for(int i = 0; i <[_eventsA count]; i++){
events *temp1 = [_eventsA objectAtIndex:i];
tempDate = temp1.eventDate;
//NSLog(#"%#", tempDate);
// NSLog(#"%#", stringDate);
// NSLog(#"%#", cd);
if([cd isEqualToString:tempDate]){
//NSLog(#"%#", tempDate);
stringType= temp1.eventType;
stringDescription = temp1.eventDescription;
}
else{
}
}
EventViewController *events = [self.storyboard instantiateViewControllerWithIdentifier:#"eventController"];
events.stringDate = stringDate;
events.stringType = stringType;
events.stringDescription = stringDescription;
[self.navigationController pushViewController:events animated:YES];
}
}
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
CalendarCollectionViewCell *cell =(CalendarCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
NSDate *cellDate = [self dateForCellAtIndexPath:indexPath];
if([self isTodayDate:cellDate]) {
cell.dateNumber.backgroundColor = [UIColor redColor];
cell.dateNumber.textColor = [UIColor whiteColor];
}
else {
cell.dateNumber.backgroundColor = [UIColor clearColor];
cell.dateNumber.textColor = [UIColor blackColor];
}
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
UICollectionReusableView *reusableview = nil;
if (kind == UICollectionElementKindSectionHeader) {
HeaderCollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:#"calendarHeader" forIndexPath:indexPath];
UIFont *font = [UIFont fontWithName:#"HelveticaNeue-Light" size:12];
headerView.month.font = font;
headerView.month.textColor = [UIColor redColor];
UIView *bottomBorder = [UIView new];
bottomBorder.backgroundColor = [UIColor lightGrayColor];
bottomBorder.frame = CGRectMake(0, headerView.frame.size.height - 1, headerView.frame.size.width, 1);
[headerView addSubview:bottomBorder];
NSDateFormatter *headerDateFormatter = [[NSDateFormatter alloc] init];
headerDateFormatter.calendar = _calendar;
headerDateFormatter.dateFormat = [NSDateFormatter dateFormatFromTemplate:#"yyyy LLLL" options:0 locale:_calendar.locale];
NSString *headerTitle = [headerDateFormatter stringFromDate:[self firstOfMonthForSection:indexPath.section]].uppercaseString;
headerView.month.text = headerTitle;
reusableview = headerView;
}
return reusableview;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
CGFloat width = self.view.frame.size.width / 7.0;
CGFloat height = width;
return CGSizeMake(width, height);
}
- (void)viewWillLayoutSubviews {
[super viewWillLayoutSubviews];
UICollectionViewFlowLayout *flowLayout = (id)self.calendarCollectionView.collectionViewLayout;
[flowLayout invalidateLayout]; //force the elements to get laid out again with the new size
}
// Calendar methods
- (NSDate *)firstOfMonthForSection:(NSInteger)section
{
NSDateComponents *offset = [NSDateComponents new];
offset.month = section;
return [_calendar dateByAddingComponents:offset toDate:_firstDate options:0];
}
- (NSDate *)dateForCellAtIndexPath:(NSIndexPath *)indexPath
{
NSDate *firstOfMonth = [self firstOfMonthForSection:indexPath.section];
NSInteger ordinalityOfFirstDay = [_calendar ordinalityOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitWeekOfMonth forDate:firstOfMonth];
NSDateComponents *dateComponents = [NSDateComponents new];
dateComponents.day = (1 - ordinalityOfFirstDay) + indexPath.item;
return [_calendar dateByAddingComponents:dateComponents toDate:firstOfMonth options:0];
}
- (BOOL)isEnabledDate:(NSDate *)date
{
NSDate *clampedDate = [self clampDate:date toComponents:(NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay)];
if (([clampedDate compare:_firstDate] == NSOrderedAscending) || ([clampedDate compare:_lastDate] == NSOrderedDescending)) {
return NO;
}
return YES;
}
- (NSDate *)clampDate:(NSDate *)date toComponents:(NSUInteger)unitFlags
{
NSDateComponents *components = [_calendar components:unitFlags fromDate:date];
return [_calendar dateFromComponents:components];
}
- (BOOL)isTodayDate:(NSDate *)date
{
return [self clampAndCompareDate:date withReferenceDate:[NSDate date]];
}
- (BOOL)isSelectedDate:(NSDate *)date
{
if (!_selectedDate) {
return NO;
}
return [self clampAndCompareDate:date withReferenceDate:_selectedDate];
}
- (BOOL)clampAndCompareDate:(NSDate *)date withReferenceDate:(NSDate *)referenceDate
{
NSDate *refDate = [self clampDate:referenceDate toComponents:(NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay)];
NSDate *clampedDate = [self clampDate:date toComponents:(NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay)];
return [refDate isEqualToDate:clampedDate];
}
#pragma mark - NSXMLParser Delegate
- (void) parserDidStartDocument:(NSXMLParser *)parser {
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
if ([elementName isEqualToString:#"event"])
_currentevent = [[events alloc] init];
}
-(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
_currentNodeContent = (NSMutableString *) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if([elementName isEqualToString:#"type"]) {
_currentevent.eventType = _currentNodeContent;
}
if([elementName isEqualToString:#"date"]) {
_currentevent.eventDate = _currentNodeContent;
}
if([elementName isEqualToString:#"description"]) {
_currentevent.eventDescription = _currentNodeContent;
}
if([elementName isEqualToString:#"event"]) {
[_eventsA addObject:_currentevent];
}
}
- (void) parserDidEndDocument:(NSXMLParser *)parser {
}
#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.
if ([segue.identifier isEqualToString:#"segueAdd"]) {
AddViewController *modalVC = (AddViewController *)segue.destinationViewController;
// modalVC.cVC = self;
modalVC.sDate = _selectedDate;
}
}
- (IBAction)todayButton:(id)sender {
UICollectionViewLayoutAttributes *attributes = [_calendarCollectionView layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:_initialSection]];
CGRect rect = attributes.frame;
[_calendarCollectionView setContentOffset:CGPointMake(_calendarCollectionView.frame.origin.x, rect.origin.y - 32) animated:YES];
}
- (IBAction)addButton:(id)sender {
[self performSegueWithIdentifier:#"segueAdd" sender:self];
}
#end
This is my view controller where I'm adding events to sqlite
#import "AddViewController.h"
#import "CalendarViewController.h"
#interface AddViewController ()
#end
#implementation AddViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#"This is the Date:%#", _sDate);
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = dirPaths[0];
// Build the path to the database file
_databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent:#"ev.db"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: _databasePath ] == NO) {
const char *dbpath = [_databasePath UTF8String];
_status.text = #"No TABLE";
if (sqlite3_open(dbpath, &_evDB) == SQLITE_OK) {
char *errMsg;
const char *sql_stmt = "CREATE TABLE IF NOT EXISTS EVENT (TYPE TEXT, DESCRIPTION TEXT, DATE VARCHAR(255))";
if (sqlite3_exec(_evDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK) {
_status.text = #"Failed to create table";
}
sqlite3_close(_evDB);
} else {
_status.text = #"Failed to open/create database";
}
}
// Do any additional setup after loading the view.
// [CalendarViewController.view.eventsA addObject:_currentevent];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *) event {
UITouch *touch = [[event allTouches] anyObject];
if ([_etype isFirstResponder] && (_etype != touch.view)) {
// _inputText lost focus - close keyboard
[_etype resignFirstResponder];
}
if ([_edescription isFirstResponder] && (_edescription != touch.view)) {
// _inputText lost focus - close keyboard
[_edescription resignFirstResponder];
}
[super touchesBegan:touches withEvent:event];
}
- (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.
if ([segue.identifier isEqualToString:#"goBack"]) {
CalendarViewController *destViewController = (CalendarViewController *)segue.destinationViewController;
destViewController.myDB = _evDB;
destViewController.databasesPath = _databasePath;
destViewController.eventDate = _cd;
destViewController.eventType = _type1;
destViewController.eventDescription = _d1;
destViewController.eventsA = _mArray;
}
}
- (IBAction)addEvent:(id)sender {
// NSMutableArray *temporaryArray = [NSMutableArray arrayWithObject:_sDate];
//= [NSMutableArray arrayWithObject:selectedRow];
// NSLog(#"%#", _sDate);
//NSLog(#"%#", type);
//NSLog(#"%#", description);
//_cVC.eventsA = temporaryArray;
_type1 = [[NSString alloc]initWithString:[_etype text]];
_d1 = [[NSString alloc]initWithString:[_edescription text]];
// NSLog(#"%#", type1);
//NSLog(#"%#", description);
sqlite3_stmt *statement;
const char *dbpath = [_databasePath UTF8String];
NSDateFormatter *fm = [[NSDateFormatter alloc] init];
fm.dateFormat = #"yyyy-MM-dd";
_cd = [fm stringFromDate:_sDate];
NSLog(#"%#" , _cd);
// save
if (sqlite3_open(dbpath, &_evDB) == SQLITE_OK) {
NSString *insertSQL = [NSString stringWithFormat:#"INSERT INTO EVENT VALUES (\"%#\", \"%#\", \"%#\")", _type1, _d1, _cd];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(_evDB, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE) {
_status.text = #"Event added";
_etype.text = #"";
_edescription.text = #"";
// UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
/*CalendarViewController *destViewController = [storyboard instantiateViewControllerWithIdentifier:#"ViewController"];
destViewController.myDB = _myDB;
destViewController.databasesPath = _databasePath;
destViewController.eventDate = cd;
destViewController.eventType = type1;
destViewController.eventDescription = description;
*/
// super.navigationController.viewDidLoad;
[self.navigationController popToRootViewControllerAnimated:YES];
//[self performSegueWithIdentifier:#"goBack" sender:self];
// CalendarViewController *cal = [self.storyboard instantiateViewControllerWithIdentifier:#"ViewController"];
//[self.navigationController pushViewController:cal animated:YES];
// _cevent.eventType =_type1;
//_cevent.eventDate = _cd;
//_cevent.eventDescription = _d1;
//[_mArray addObject:_cevent];
} else {
_status.text = #"Failed to add event";
}
sqlite3_finalize(statement);
sqlite3_close(_evDB);
}
}
#end

if (![_eventsA containsObject:_currentevent]) {
[self.eventsA addObject:_currentevent];
Problem 1. After one [self.eventsA addObject:_currentevent], [_eventsA containsObject:_currentevent] will return YES.
Problem 2. NSMutableArray stores pointers to objects and doesn't copy an object when it is added. If you add _currentevent to self.eventsA and then change the properties of _currentevent, the properties of the added _currentevent will change. If you remove if (![_eventsA containsObject:_currentevent]) and keep adding the same object, which is possible, all elements of _eventsA will have the properties of the last _currentevent.
Solution: create a new local event object in each iteration of the while loop.

Related

Uncheck (unfavorite) items in Favorites Table View

I have a tableview that displays a list of "favorited" items. Users favorite items in another tableview, and favorited items are listed in this tableview (FavoritesTableView.m).
For some reason, I can't get checked items (favorited items) to "uncheck" from the FavoritesTableView? What am I missing?
See the .m file below...
FavoritesViewController.h
#import <UIKit/UIKit.h>
#import "StrainTableCell.h"
#interface FavoritesViewController : UITableViewController
{
}
#property (strong, nonatomic) NSArray *favoritesArrayset;
#property (strong, nonatomic) IBOutlet UITableView *favoritesTable;
#property (nonatomic, strong) NSMutableArray * favoritesArray;
- (IBAction)backbuttonpressed: (UIBarButtonItem *)sender;
#end
FavoritesViewController.m
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:YES];
if (favoritesArray == Nil)
{
favoritesArray = [[NSMutableArray alloc] init];
}
else
{
[favoritesArray removeAllObjects];
}
NSData *dataSave = [[NSUserDefaults standardUserDefaults] objectForKey:#"strains"];
if (dataSave != Nil)
{
favoritesArrayset = [NSKeyedUnarchiver unarchiveObjectWithData:dataSave];
for (NSDictionary *item in favoritesArrayset)
{
BOOL isChecked = [[item objectForKey:#"checked"] boolValue];
if (isChecked == YES )
{
[favoritesArray addObject:item];
}
}
}
[favoritesTable reloadData];
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return favoritesArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSArray *Strains = [favoritesArray copy];
NSArray *dataArray = [favoritesArray copy];
static NSString *strainTableIdentifier = #"StrainTableCell";
StrainTableCell *cell = (StrainTableCell *)[tableView dequeueReusableCellWithIdentifier:strainTableIdentifier];
if (cell == nil)
{
cell = [[StrainTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strainTableIdentifier] ;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"StrainTableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
cell.titleLabel.text = [[Strains objectAtIndex:indexPath.row] objectForKey:#"Title"];
cell.descriptionLabel.text = [[Strains objectAtIndex:indexPath.row] objectForKey:#"Description"];
cell.ratingLabel.text = [[Strains objectAtIndex:indexPath.row] objectForKey:#"Rating"];
cell.ailmentLabel.text = [[Strains objectAtIndex:indexPath.row] objectForKey:#"Ailment"];
cell.actionLabel.text = [[Strains objectAtIndex:indexPath.row] objectForKey:#"Action"];
cell.ingestLabel.text = [[Strains objectAtIndex:indexPath.row] objectForKey:#"Ingestion"];
cell.whatCellamI = [NSNumber numberWithInt:indexPath.row];
NSMutableDictionary *item = [dataArray objectAtIndex:indexPath.row];
cell.textLabel.text = [item objectForKey:#"text"];
[item setObject:cell forKey:#"StrainTableCell"];
}
BOOL checked = [[item objectForKey:#"checked"] boolValue];
UIImage *image = (checked) ? [UIImage imageNamed:#"checked.png"] : [UIImage imageNamed:#"unchecked.png"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
CGRect frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
button.frame = frame;
[button setBackgroundImage:image forState:UIControlStateNormal];
[button addTarget:self action:#selector(checkButtonTapped:event:) forControlEvents:UIControlEventTouchUpInside];
button.backgroundColor = [UIColor clearColor];
cell.accessoryView = button;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
StrainDetailViewController *detailViewController = [[StrainDetailViewController alloc]
initWithNibName:#"StrainDetailViewController" bundle:nil];
detailViewController.title = [[favoritesArray objectAtIndex:indexPath.row] objectForKey:#"Title"];
detailViewController.strainDetail = [favoritesArray objectAtIndex:indexPath.row];
[self.navigationController pushViewController:detailViewController animated:YES];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 82;
}
- (IBAction)backbuttonpressed:(id)sender
{
[self.view.window.rootViewController dismissViewControllerAnimated:YES completion:nil];
}
- (void)checkButtonTapped:(id)sender event:(id)event
{
NSLog(#"made it here and event is %#",event);
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:self.favoritesTable];
NSIndexPath * indexPath ;
indexPath = [self.favoritesTable indexPathForRowAtPoint: currentTouchPosition];
NSLog(#"indexpath is below");
NSLog(#"%#",indexPath);
if (indexPath != Nil)
{
NSMutableDictionary *item = [favoritesArray objectAtIndex:indexPath.row];
BOOL isItChecked = [[item objectForKey:#"checked"] boolValue];
/*
if (isItChecked == NO) {
NSMutableArray *tmpArray = [[NSMutableArray alloc] init];
NSMutableArray *tmpArray2 = [[NSMutableArray alloc] initWithArray:[favoritesArray allObjects]];
NSString *text1 = [item objectForKey:#"Title"];
for (NSDictionary * object in tmpArray2) {
NSString *text2 = [object objectForKey:#"Title"];
if (![text1 isEqualToString:text2]) {
[tmpArray addObject:object];
}
}
// [favoritesArray removeAllObjects];
favoritesArray = [tmpArray copy];
}
*/
NSMutableArray *quickArray = [[NSMutableArray alloc] initWithArray:favoritesArray];
[quickArray replaceObjectAtIndex:indexPath.row withObject:item];
[item setObject:[NSNumber numberWithBool:!isItChecked] forKey:#"checked"];
favoritesArray = [quickArray copy];
// [self.favoritesArray addObject:item];
// NSLog(#"you have added %d items to favorites", self.favoritesArray.count);
[favoritesTable reloadData];
}
#end
In your .h take one NSMutableDictionary and do property to it.
In your .m synthesize it,and in viewdidLoad alloc the Dictionary.
Now put this below code in CellForRowAtIndex
if([idDictonary objectForKey:[NSString stringWithFormat:#"%d",[indexPath row]]])
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
and put this below code in DidSelectRowAtIndex
UITableViewCell *thisCell = [tableView cellForRowAtIndexPath:indexPath];
if (thisCell.accessoryType == UITableViewCellAccessoryNone)
{
thisCell.accessoryType = UITableViewCellAccessoryCheckmark;
[idDictonary setValue:[dataArray objectAtIndex:indexPath.row] forKey:[NSString stringWithFormat:#"%d",[indexPath row]]];
}
else
{
if([idDictonary objectForKey:[NSString stringWithFormat:#"%d",[indexPath row]]])
{
[idDictonary removeObjectForKey:[NSString stringWithFormat:#"%d",[indexPath row]]];
thisCell.accessoryType = UITableViewCellAccessoryNone;
}
}
[myTableView reloadData];
NSLog(#"idDictonary = %#",idDictonary);
i hope this will helps u Brittany...
Every time -tableView:cellForRowAtIndexPath: runs, you create a new button, set it to the desired properties and … throw it away. (Seems to be the running joke this week.) You have to use the existing button.

Iphone uitextfield auto format like contacts app tag issue

I have a form screen on my iphone and I am trying to replicate the Iphone Contacts app where it will auto complete the following format for the phone number:
(233)323-2323.
I am very close I am able to see the format update in the textfield but the 4 other text fields are not working now. I am unable to edit them. I narrowed it down to the shouldchangecharactersinrange function.
Please see code below.
Thanks.
quick look at the method:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if(([textField tag] == 2)){
int length = [self getLength:textField.text];
//NSLog(#"Length = %d ",length);
if(length == 10)
{
if(range.length == 0)
return NO;
}
if(length == 3)
{
NSString *num = [self formatNumber:textField.text];
textField.text = [NSString stringWithFormat:#"(%#) ",num];
if(range.length > 0)
textField.text = [NSString stringWithFormat:#"%#",[num substringToIndex:3]];
}
else if(length == 6)
{
NSString *num = [self formatNumber:textField.text];
//NSLog(#"%#",[num substringToIndex:3]);
//NSLog(#"%#",[num substringFromIndex:3]);
textField.text = [NSString stringWithFormat:#"(%#) %#-",[num substringToIndex:3],[num substringFromIndex:3]];
if(range.length > 0)
textField.text = [NSString stringWithFormat:#"(%#) %#",[num substringToIndex:3],[num substringFromIndex:3]];
}
return YES;
}else if([textField tag] != 1){
return NO;
}
}
-(NSString*)formatNumber:(NSString*)mobileNumber
{
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"(" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#")" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"-" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"+" withString:#""];
NSLog(#"%#", mobileNumber);
int length = [mobileNumber length];
if(length > 10)
{
mobileNumber = [mobileNumber substringFromIndex: length-10];
NSLog(#"%#", mobileNumber);
}
return mobileNumber;
}
-(int)getLength:(NSString*)mobileNumber
{
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"(" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#")" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"-" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"+" withString:#""];
int length = [mobileNumber length];
return length;
}
Firstcontroller.h
#interface FirstTVContoller : UIViewController <UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate, UIPickerViewDataSource,UIPickerViewDelegate>{
NSMutableArray *items;
NSMutableArray *titles;
NSMutableArray *section2items;
NSMutableArray *dataArray;
UITableView *table;
contactTitle *title;
//launch title picker
UIPickerView *titlePicker;
UILabel *titleLabel;
UITextField *titleField;
UIActionSheet *actionSheet;
UIPickerView *pickerView;
UITextField *textField;
UITextField *FirstnameTextfield;
UITextField *LastnameTextfield;
UITextField *CompanyTextfield;
UITextField *phoneTextfield;
//the scrollview
UIScrollView *scrollview;
}
//attributes for title picker
#property (strong, nonatomic) NSArray * titlecategories;
#property (strong, nonatomic) NSArray * titleidSlot;
#end
FirstTVController.m
//
// FirstTVContoller.m
// TwoTableViews
#implementation FirstTVContoller
#synthesize titleidSlot;
#synthesize titlecategories;
- (BOOL) connectedToNetwork
{
// Create zero addy
struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;
// Recover reachability flags
SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
SCNetworkReachabilityFlags flags;
BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
CFRelease(defaultRouteReachability);
if (!didRetrieveFlags)
{
//NSLog(#"Error. Could not recover network reachability flags");
return NO;
}
BOOL isReachable = flags & kSCNetworkFlagsReachable;
BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
BOOL nonWiFi = flags & kSCNetworkReachabilityFlagsTransientConnection;
NSURL *testURL = [NSURL URLWithString:SERVERNAME];
NSURLRequest *testRequest = [NSURLRequest requestWithURL:testURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20.0];
NSURLConnection *testConnection = [[NSURLConnection alloc] initWithRequest:testRequest delegate:self];
return ((isReachable && !needsConnection) || nonWiFi) ? (testConnection ? YES : NO) : NO;
}
-(void)viewDidLoad{
[super viewDidLoad];
// scrollview = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 300, 500)];
// scrollview.pagingEnabled = YES;
//
// //[scrollview addSubview:self.view];
// [self.view addSubview:scrollview];
table.scrollEnabled = YES;
dataArray = [[NSMutableArray alloc] init];
titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 290, 30)];
//dropper
titleField = [[UITextField alloc] initWithFrame:CGRectMake(10, 2, 300, 30)];
titleField.layer.cornerRadius = 8;
titleField.backgroundColor = [UIColor clearColor];
NSArray *firstItemsArray = [[NSArray alloc] initWithObjects:#"1",#"2", nil];
NSDictionary *firstItemsArrayDict = [NSDictionary dictionaryWithObject:firstItemsArray forKey:#"data"];
[dataArray addObject:firstItemsArrayDict];
//Second section dat
NSArray *secondItemsArray = [[NSArray alloc] initWithObjects:#"1", nil];
NSDictionary *secondItemsArrayDict = [NSDictionary dictionaryWithObject:secondItemsArray forKey:#"data"];
[dataArray addObject:secondItemsArrayDict];
NSArray *thirdItemsArray = [[NSArray alloc] initWithObjects:#"1",#"2",#"3", nil];
NSDictionary *thirdItemsArrayDict = [NSDictionary dictionaryWithObject:thirdItemsArray forKey:#"data"];
[dataArray addObject:thirdItemsArrayDict];
NSLog(#"the dataArray%#",dataArray);
if([self connectedToNetwork]){
dispatch_async(kBgQueue, ^{
//build the url of strings
FULLURL = [SERVERNAME stringByAppendingFormat:ushTitleLink];
//create the url
NSURL *url = [[NSURL alloc] initWithString:FULLURL];
//NSLog(#"here title url%#",url);
//get the data from the url
NSData* data = [NSData dataWithContentsOfURL: url];
NSLog(#"here%#",data);
//get the data from the url
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
NSLog(#"titleid:%#",TITLEID);
NSLog(#"title categories:%#",titlecategories);
});
[table setBounces:NO];
}else{
dispatch_async(dispatch_get_main_queue(), ^ {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: #"Please Check your internet connection"
message:#"Enable your internet connection"
delegate: nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
});
}
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return [dataArray count];
}
-(NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
//Number of rows it should expect should be based on the section
NSDictionary *dictionary = [dataArray objectAtIndex:section];
NSArray *array = [dictionary objectForKey:#"data"];
return [array count];
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if(indexPath.section == 1){
cell.backgroundColor =[UIColor colorWithPatternImage:[UIImage imageNamed:#"longdropper300.png"]];
}
else{
cell.backgroundColor = [UIColor whiteColor];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
textField = [[UITextField alloc] initWithFrame:CGRectMake(15, 10, 290, 30)];
static NSString *cellValue = #"Cell";
UITableViewCell *cell =nil;
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellValue];
}
cell.selectionStyle = UITableViewCellSelectionStyleGray;
if ([indexPath section] == 0) {
//cellValue=[items objectAtIndex:indexPath.row];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.selectionStyle= UITableViewCellSelectionStyleNone;
//textField.tag = 1;
textField.adjustsFontSizeToFitWidth = YES;
textField.textColor = [UIColor blackColor];
if(indexPath.section == 0){
//textfield for email
if ([indexPath row] == 0) {
textField.tag = 1;
textField.text = EMAIL;
textField.textColor= [UIColor blackColor];
textField.placeholder = #"Email: example#gmail.com";
textField.keyboardType = UIKeyboardTypeEmailAddress;
textField.returnKeyType = UIReturnKeyNext;
}
//textfield for phone number
else {
textField.tag = 2;
if ([PHONENUMBER isEqual: [NSNull null]] && PHONENUMBER == nil && PHONENUMBER == NULL && [PHONENUMBER isEqual: #""]){
NSLog(#"phone is empty%#",PHONENUMBER);
//[PHONENUMBER isEqual:#"frank"];
}else{
NSLog(#"phone is not empty%#",PHONENUMBER);
textField.text = PHONENUMBER;
}
textField.placeholder = #"Phone: (xxx)xxx-xxxx";
textField.keyboardType = UIKeyboardTypeDefault;
textField.returnKeyType = UIReturnKeyDefault;
textField.secureTextEntry = NO;
}
textField.backgroundColor = [UIColor whiteColor];
//textField.autocorrectionType = UITextAutocorrectionTypeNo; // no auto correction support
//textField.autocapitalizationType = UITextAutocapitalizationTypeNone; // no auto capitalization support
textField.textAlignment = UITextAlignmentLeft;
//textField.clearButtonMode = UITextFieldViewModeNever; // no clear 'x' button to the right
[textField setEnabled: YES];
textField.delegate = self;
[cell addSubview:textField];
}
}
if(indexPath.section == 1){
[titleField setTextColor:[UIColor whiteColor]];
titleField.tag = 3;
titleField.placeholder = #"Select Contact Title";
titleField.returnKeyType = UIReturnKeyNext;
//titleField == textField.tag = 3;
if ([TITLENAME isEqual: [NSNull null]]){
NSLog(#"titlename is empty%#",TITLENAME);
}else{
NSLog(#"titlename is not empty%#",TITLENAME);
titleField.text = TITLENAME;
}
titleField.keyboardType = UIKeyboardTypeDefault;
titleField.returnKeyType = UIReturnKeyDone;
titleField.secureTextEntry = NO;
titleField.autocorrectionType = UITextAutocorrectionTypeNo; // no auto correction support
titleField.autocapitalizationType = UITextAutocapitalizationTypeNone; // no auto capitalization support
titleField.textAlignment = UITextAlignmentCenter;
titleField.clearButtonMode = UITextFieldViewModeNever; // no clear 'x' button to the right
[titleField setEnabled: NO];
titleField.delegate = self;
[cell addSubview:titleField];
NSLog(#"here is the titlename%#",TITLENAME);
}
if(indexPath.section == 2){
if ([indexPath row] == 0) {
textField.tag = 4;
textField.placeholder = #"First Name";
cell.selectionStyle= UITableViewCellSelectionStyleNone;
if ([FIRSTNAME isEqual: [NSNull null]]){
NSLog(#"firstname is empty%#",FIRSTNAME);
textField.text = #"";
}else{
textField.text = FIRSTNAME;
}
textField.keyboardType = UIKeyboardTypeEmailAddress;
textField.returnKeyType = UIReturnKeyNext;
}
if([indexPath row] == 1){
textField.tag = 5;
textField.placeholder = #"Last Name";
if ([LASTNAME isEqual: [NSNull null]]){
NSLog(#"lastname is empty%#",LASTNAME);
textField.text = #"";
}else{
textField.text = LASTNAME;
}
textField.keyboardType = UIKeyboardTypeDefault;
textField.returnKeyType = UIReturnKeyNext;
//textField.secureTextEntry = NO;
}
if([indexPath row] == 2){
textField.tag = 6;
textField.placeholder = #"Company";
if ([COMPANY isEqual: [NSNull null]]){
NSLog(#"company is empty%#",COMPANY);
textField.text = #"";
}
else{
textField.text = COMPANY;
}
textField.keyboardType = UIKeyboardTypeDefault;
textField.returnKeyType = UIReturnKeyDone;
textField.secureTextEntry = NO;
}
//]textField.backgroundColor = [UIColor whiteColor];
textField.autocorrectionType = UITextAutocorrectionTypeNo; // no auto correction support
textField.autocapitalizationType = UITextAutocapitalizationTypeNone; // no auto capitalization support
textField.textAlignment = UITextAlignmentLeft;
textField.clearButtonMode = UITextFieldViewModeNever; // no clear 'x' button to the right
[textField setEnabled: YES];
textField.delegate = self;
[cell addSubview:textField];
}
return cell;
}
//Change the Height of title cell drop down
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
if (indexPath.section == 1) {
if (indexPath.row == 0) {
return 30;
}
}
return 45;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
if(([textField tag] == 1)){
NSString *emailRegEx = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegEx];
//Valid email address
if ([emailTest evaluateWithObject:textField.text] == YES)
{
EMAIL = [textField.text copy];
NSLog(#"here is the email%#",EMAIL);
}
else
{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: #"Bad Email"
message: #"Please Re-enter the email address with a valid email"
delegate: nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
textField.text = nil;
NSLog(#"email not in proper format");
}
}
if(([textField tag] == 2)){
//NSString *phoneRegex = #"[235689][0-9]{6}([0-9]{3})?";
//NSPredicate *phoneTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", phoneRegex];
//valid email address
//if ([phoneTest evaluateWithObject:textField.text] == YES)
// {
//if(PHONENUMBER != nil){
NSString *tempString = [textField.text copy];
NSString *unformatted = tempString;
NSLog(#"unformatted phonenumber%#",unformatted);
NSArray *stringComponents = [NSArray arrayWithObjects:[unformatted substringWithRange:NSMakeRange(0, 3)],
[unformatted substringWithRange:NSMakeRange(3, 3)],
[unformatted substringWithRange:NSMakeRange(6, [unformatted length]-6)], nil];
NSString *formattedString = [NSString stringWithFormat:#"(%#)%#-%#", [stringComponents objectAtIndex:0], [stringComponents objectAtIndex:1], [stringComponents objectAtIndex:2]];
NSLog(#"Formatted Phone Number: %#", formattedString);
PHONENUMBER = formattedString;
NSLog(#"here is the phone number %#",PHONENUMBER);
// }
// else
// {
// NSLog(#"Phone Number Invalid");
// UIAlertView *alert = [[UIAlertView alloc]
// initWithTitle: #"xxx-xxx-xxxx"
// message: #"Please enter a valid phone number"
// delegate: nil
// cancelButtonTitle:#"OK"
// otherButtonTitles:nil];
// [alert show];
// textField.text = nil;
// }
}
if(([textField tag] == 4)){
FIRSTNAME = [textField.text copy];
NSLog(#"here is the firstName%#",FIRSTNAME);
}
if(([textField tag] == 5)){
LASTNAME = [textField.text copy];
NSLog(#"here is the Last Name%#",LASTNAME);
}
if(([textField tag] == 6)){
COMPANY = [textField.text copy];
NSLog(#"here is the Company%#",COMPANY);
}
return YES;
}
-(BOOL)textFieldShouldReturn:(UITextField*)textField;
{
NSInteger nextTag = textField.tag + 1;
// Try to find next responder
UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
if (nextResponder) {
// Found next responder, so set it.
[nextResponder becomeFirstResponder];
} else {
// Not found, so remove keyboard.
[textField resignFirstResponder];
}
return NO; // We do not want UITextField to insert line-breaks.
}
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
title = [[contactTitle alloc] initWithDictionary:json];
//NSLog(#"here is the dictionary from json: %#", json);
NSLog(#"here is title that was the json %#", title);
NSLog(#"here is the title from json: %#", title.cTitle);
NSLog(#"here is the title id from json %#", title.cTitleID);
}
//PickerViewController.m
- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
dispatch_queue_t downloadQueue = dispatch_queue_create("data loader", NULL);
dispatch_async(downloadQueue, ^{
TITLENAME = [title.cTitle objectAtIndex:row], row;
//NSLog(#"here is the selected title%#", TITLENAME);
TITLEID = [title.cTitleID objectAtIndex:row], row;
//NSLog(#"here is the selected title%#", TITLEID);
});
//thePickerView.hidden = YES;
}
//PickerView
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView {
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component {
return [title.cTitle count];
}
- (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return [title.cTitle
objectAtIndex:row];
}
- (void)fetchedContactIDData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSLog(#"here is the login info from json: %#", json);
// NSString *FALSELOGIN;
CONTACTID = [json valueForKey:#"contactid"];
NSLog(#"CONTACT ID: %#", CONTACTID);
// LOGINID = [json valueForKey:#"login"];
// NSLog(#"LOGIN ID: %#", LOGINID);
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//get the country selected
//NSString *selectedCell = nil;
if(indexPath.section == 1){
titleField.text = #"Select Contact Title";
NSLog(#"you selected:%#",TITLENAME);
actionSheet = [[UIActionSheet alloc] initWithTitle:nil
delegate:nil
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:nil];
[actionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
CGRect pickerFrame = CGRectMake(0, 40, 0, 0);
pickerView = [[UIPickerView alloc] initWithFrame:pickerFrame];
pickerView.showsSelectionIndicator = YES;
pickerView.dataSource = self;
pickerView.delegate = self;
[actionSheet addSubview:pickerView];
UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:#"Cancel"]];
closeButton.momentary = YES;
closeButton.frame = CGRectMake(260, 7.0f, 50.0f, 30.0f);
closeButton.segmentedControlStyle = UISegmentedControlStyleBar;
closeButton.tintColor = [UIColor blackColor];
[closeButton addTarget:self action:#selector(dismissActionSheet:) forControlEvents:UIControlEventValueChanged];
[actionSheet addSubview:closeButton];
//[actionSheet showInView:[[UIApplication sharedApplication] keyWindow]];
[actionSheet showInView:self.view];
[actionSheet setBounds:CGRectMake(0, 0, 320, 485)];
}else{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if(([textField tag] == 2)){
int length = [self getLength:textField.text];
//NSLog(#"Length = %d ",length);
if(length == 10)
{
if(range.length == 0)
return NO;
}
if(length == 3)
{
NSString *num = [self formatNumber:textField.text];
textField.text = [NSString stringWithFormat:#"(%#) ",num];
if(range.length > 0)
textField.text = [NSString stringWithFormat:#"%#",[num substringToIndex:3]];
}
else if(length == 6)
{
NSString *num = [self formatNumber:textField.text];
//NSLog(#"%#",[num substringToIndex:3]);
//NSLog(#"%#",[num substringFromIndex:3]);
textField.text = [NSString stringWithFormat:#"(%#) %#-",[num substringToIndex:3],[num substringFromIndex:3]];
if(range.length > 0)
textField.text = [NSString stringWithFormat:#"(%#) %#",[num substringToIndex:3],[num substringFromIndex:3]];
}
return YES;
}else if([textField tag] != 1){
return NO;
}
}
-(NSString*)formatNumber:(NSString*)mobileNumber
{
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"(" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#")" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"-" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"+" withString:#""];
NSLog(#"%#", mobileNumber);
int length = [mobileNumber length];
if(length > 10)
{
mobileNumber = [mobileNumber substringFromIndex: length-10];
NSLog(#"%#", mobileNumber);
}
return mobileNumber;
}
-(int)getLength:(NSString*)mobileNumber
{
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"(" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#")" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"-" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"+" withString:#""];
int length = [mobileNumber length];
return length;
}
- (void)dismissActionSheet:(id)sender{
[actionSheet dismissWithClickedButtonIndex:0 animated:YES];
//pickerButton.titleLabel.text = TITLENAME;
//titleLabel.text= TITLENAME;
titleField.text = TITLENAME;
[titleLabel reloadInputViews];
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
[titlePicker removeConstraints:titlePicker];
[titlePicker removeFromSuperview];
}
#end
after reviewing your code i found one thing see below here is the problem
if(([textField tag] == 2)){
//something
return YES;
}
else if([textField tag] != 1){
return NO;
}
in else if block you keep return NO it means it doesn't take any input text , change that one to return YES it'l work.

My tableView methods have poor performance

I have two problems (in fact one - my code sucks):
My table takes a long time to load(about 5 seconds)
She is dreadfully poor
Any ideas?
My tableView methods:
// Table
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
RefreshDelegate *RefreshProtocol = [[RefreshDelegate new] autorelease];
RefreshProtocol.delegate = self;
return [[RefreshProtocol returnDataForTable] count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
RefreshDelegate *RefreshProtocol = [[RefreshDelegate new] autorelease];
RefreshProtocol.delegate = self;
NSArray *curent = [self curent:section];
return [curent count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
RefreshDelegate *RefreshProtocol = [[RefreshDelegate new] autorelease];
RefreshProtocol.delegate = self;
return [[[RefreshProtocol returnDataForTable] allKeys] objectAtIndex:section];
}
- (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] autorelease];
}
NSArray *curent = [self curent:indexPath.section];
cell.textLabel.text = [curent objectAtIndex:indexPath.row];
return cell;
}
- (NSArray*)curent:(NSInteger)index {
RefreshDelegate *RefreshProtocol = [[RefreshDelegate new] autorelease];
RefreshProtocol.delegate = self;
NSArray *keys = [[RefreshProtocol returnDataForTable] allKeys];
NSString *curentKey = [keys objectAtIndex:index];
NSArray *curent = [[RefreshProtocol returnDataForTable] objectForKey:curentKey];
return curent;
}
My RefreshProtocol methods:
#define MaxCountPair 7
-(NSDictionary *)returnDataForTable{
NSMutableArray *day_1 = [NSMutableArray arrayWithCapacity:MaxCountPair];
NSMutableArray *day_2 = [NSMutableArray arrayWithCapacity:MaxCountPair];
NSMutableArray *day_3 = [NSMutableArray arrayWithCapacity:MaxCountPair];
NSMutableArray *day_4 = [NSMutableArray arrayWithCapacity:MaxCountPair];
NSMutableArray *day_5 = [NSMutableArray arrayWithCapacity:MaxCountPair];
NSMutableArray *day_6 = [NSMutableArray arrayWithCapacity:MaxCountPair];
// Analysis db and write array today
NSArray *array = [SQLiteAccess selectManyRowsWithSQL:#"select * from schedule"];
for (int i = 0; i < [array count]; i++) {
NSDictionary *dictionary = [array objectAtIndex:i];
if ([self checkOverlapDigit:[[[NSUserDefaults standardUserDefaults] valueForKey:#"numberWeek"] objectForKey:#"numberWeek"]:[dictionary objectForKey:#"week"]] && [self checkOverlapDigit:[self subgroupToInt]:[dictionary objectForKey:#"subgroup"]]) {
if ([self checkDay:[[dictionary objectForKey:#"day"] intValue]]) {
[day_1 addObject:[dictionary objectForKey:#"subject"]];
}
else {
if ([self checkDay:[[dictionary objectForKey:#"day"] intValue] - 1]) {
[day_2 addObject:[dictionary objectForKey:#"subject"]];
}
else {
if ([self checkDay:[[dictionary objectForKey:#"day"] intValue] - 2]) {
[day_3 addObject:[dictionary objectForKey:#"subject"]];
}
else {
if ([self checkDay:[[dictionary objectForKey:#"day"] intValue] - 3]) {
[day_4 addObject:[dictionary objectForKey:#"subject"]];
}
else {
if ([self checkDay:[[dictionary objectForKey:#"day"] intValue] - 4]) {
[day_5 addObject:[dictionary objectForKey:#"subject"]];
}
else {
if ([self checkDay:[[dictionary objectForKey:#"day"] intValue] - 5]) {
[day_6 addObject:[dictionary objectForKey:#"subject"]];
}
}
}
}
}
}
}
}
NSDictionary *days = [NSDictionary dictionaryWithObjectsAndKeys:day_1, #"1", day_2, #"2", day_3, #"3", day_4, #"4", day_5, #"5", day_6, #"6", nil];
return days;
}
-(NSString *)removeAllButDigit:(NSString *)originalString{
// Remove all but digit
NSMutableString *strippedString = [NSMutableString
stringWithCapacity:originalString.length];
NSScanner *scanner = [NSScanner scannerWithString:originalString];
NSCharacterSet *numbers = [NSCharacterSet
characterSetWithCharactersInString:#"1234"];
while ([scanner isAtEnd] == NO) {
NSString *buffer;
if ([scanner scanCharactersFromSet:numbers intoString:&buffer]) {
[strippedString appendString:buffer];
} else {
[scanner setScanLocation:([scanner scanLocation] + 1)];
}
}
return strippedString;
}
-(BOOL)checkDay:(NSInteger)day{
NSString *currentDay = nil;
switch (day) {
case 1:
currentDay = NSLocalizedString(#"_monday", nil);
break;
case 2:
currentDay = NSLocalizedString(#"_tuesday", nil);
break;
case 3:
currentDay = NSLocalizedString(#"_wednesday", nil);
break;
case 4:
currentDay = NSLocalizedString(#"_thursday", nil);
break;
case 5:
currentDay = NSLocalizedString(#"_friday", nil);
break;
case 6:
currentDay = NSLocalizedString(#"_saturday", nil);
break;
default:
break;
}
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"EEEE"];
if ([currentDay isEqualToString:[dateFormatter stringFromDate:[NSDate date]]]) {
return YES;
}
return NO;
}
-(BOOL)checkOverlapDigit:(NSString *)smallerString:(NSString *)largerString{
if ([largerString isEqualToString:#"0"]) {
return YES;
}
NSInteger intSmaller = [[self removeAllButDigit:smallerString] intValue];
NSInteger intLarger = [[self removeAllButDigit:largerString] intValue];
while (1) {
if (intLarger % 10 != 0) {
NSInteger sedimentWeek = intLarger % 10;
if (sedimentWeek == intSmaller) {
return YES;
}
intLarger /= 10;
}
else {
if (intLarger / 10 != 0) {
intLarger /= 10;
if (intLarger == intSmaller) {
return YES;
}
}
else {
return NO;
}
}
}
}
-(NSString *)subgroupToInt{
if ([[[NSUserDefaults standardUserDefaults]objectForKey:#"subgroupValue"] isEqualToString: #"subgroupValue1"]) {
return #"1";
}
else
if ([[[NSUserDefaults standardUserDefaults]objectForKey:#"subgroupValue"] isEqualToString: #"subgroupValue2"]) {
return #"2";
}
else
if ([[[NSUserDefaults standardUserDefaults]objectForKey:#"subgroupValue"] isEqualToString: #"subgroupValue3"]) {
return #"3";
}
return #"4";
}
And SQLiteAccess class: .h, .m
For starting... you can (you have) to create you object only once!! (in the constructor? In -viewDidLoad ?)
Then in the tableView delegate methods you access your (unique) object.
EDIT:
Adds a property in your class:
#property (nonatomic, strong) RefreshDelegate* refreshProtocol;
In your -viewDidLoad method add
-(void)viewDidLoad
{
[super viewDidLoad];
self.refreshProtocol = [[RefreshDelegate new] autorelease];
self.refreshProtocol.delegate = self;
}
Now:
- (NSArray*)curent:(NSInteger)index {
NSArray *keys = [[self.refreshProtocol returnDataForTable] allKeys];
NSString *curentKey = [keys objectAtIndex:index];
NSArray *curent = [[self.refreshProtocol returnDataForTable] objectForKey:curentKey];
return curent;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSArray *curent = [self curent:section];
return [curent count];
}
... and correct the other methods...

removeObjectAtIndex crashing the app

In the .h file I have set the below line.
NSMutableArray *repArray;
In the .m file I have placed the below lines.(I put just the required lines of code for this ex)
-(void)read_data_fromDB
{
objectsForCharacters = [[NSMutableDictionary alloc]init];
sqlite3 *db = [contactAppDelegate getNewDBConnection];
NSMutableString *query = nil;
query = [NSMutableString stringWithFormat:#"select representative, title, business_name, uid from corporate where profiler_type <> 'OWN_CORPORATE' order by representative asc"];
const char *sql = [query UTF8String];
sqlite3_stmt *selectAllStmt = nil;
if(sqlite3_prepare_v2(db,sql, -1, &selectAllStmt, NULL)!= SQLITE_OK)
NSAssert1(0,#"error preparing statement",sqlite3_errmsg(db));
else
{
repArray = [[NSMutableArray alloc]init];
businessArray = [[NSMutableArray alloc]init];
titleArray = [[NSMutableArray alloc]init];
uidArray = [[NSMutableArray alloc]init];
while(sqlite3_step(selectAllStmt)==SQLITE_ROW)
{
char *chrstr =(char *)sqlite3_column_text(selectAllStmt, 0);
if(chrstr !=NULL)
{
corpRepresentative = [NSString stringWithUTF8String:chrstr];
[repArray addObject:corpRepresentative];
}
chrstr =(char *)sqlite3_column_text(selectAllStmt, 1);
if(chrstr !=NULL)
{
corpTitle = [NSString stringWithUTF8String:chrstr];
[titleArray addObject:corpTitle];
}
chrstr =(char *)sqlite3_column_text(selectAllStmt, 2);
if(chrstr !=NULL)
{
corpBusiness_name = [NSString stringWithUTF8String:chrstr];
[businessArray addObject:corpBusiness_name];
}
chrstr =(char *)sqlite3_column_text(selectAllStmt, 3);
if(chrstr !=NULL)
{
corporteUid = [NSString stringWithUTF8String:chrstr];
[uidArray addObject:corporteUid];
}
}
}
sqlite3_finalize(selectAllStmt);
sqlite3_close(db);
}
- (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];
UILongPressGestureRecognizer *longPressGesture =
[[[UILongPressGestureRecognizer alloc]
initWithTarget:self action:#selector(longPress:)] autorelease];
[cell addGestureRecognizer:longPressGesture];
}
// Configure the cell...
UILabel *txtLbl = [[UILabel alloc]initWithFrame:CGRectMake(70, 0, 175, 26)];
//[txtLbl setBackgroundColor:[UIColor greenColor]];
[txtLbl setTextAlignment:UITextAlignmentLeft];
NSString *txtStr = [repArray objectAtIndex:indexPath.row];
UIFont *fontTxtLbl = [UIFont fontWithName: #"FuturaMdBT" size:16];
[txtLbl setFont:fontTxtLbl];
[txtLbl setText:txtStr];
[cell.contentView addSubview:txtLbl];
[txtLbl release];
UILabel *txtDetailLbl = [[UILabel alloc]initWithFrame:CGRectMake(70, 27, 175, 20)];
// [txtDetailLbl setBackgroundColor:[UIColor redColor]];
[txtDetailLbl setTextAlignment:UITextAlignmentLeft];
NSString *txtDetailStr = [titleArray objectAtIndex:indexPath.row];
UIFont *fontTxtDetailLbl = [UIFont fontWithName: #"Arial" size:12];
[txtDetailLbl setFont:fontTxtDetailLbl];
[txtDetailLbl setText:txtDetailStr];
[cell.contentView addSubview:txtDetailLbl];
[txtDetailLbl release];
UILabel *txtDetailLbl1 = [[UILabel alloc]initWithFrame:CGRectMake(70, 47, 175, 20)];
//[txtDetailLbl1 setBackgroundColor:[UIColor blueColor]];
[txtDetailLbl1 setTextAlignment:UITextAlignmentLeft];
NSString *txtDetailStr1 = [businessArray objectAtIndex:indexPath.row];
UIFont *fontTxtDetailLbl1 = [UIFont fontWithName: #"Arial" size:12];
[txtDetailLbl1 setFont:fontTxtDetailLbl1];
[txtDetailLbl1 setText:txtDetailStr1];
[cell.contentView addSubview:txtDetailLbl1];
[txtDetailLbl1 release];
// cell.textLabel.text = [repArray objectAtIndex:indexPath.row];
//cell.detailTextLabel.text = [titleArray objectAtIndex:indexPath.row];
cell.imageView.image=[imagearray objectAtIndex:indexPath.row];
UIView *viewSelected = [[[UIView alloc] init] autorelease];
viewSelected.backgroundColor = [UIColor colorWithRed:224.0/255.0
green:229.0/255.0
blue:241.0/255.0
alpha:1.0];
cell.selectedBackgroundView = viewSelected;
cell.textLabel.highlightedTextColor=[UIColor colorWithRed:46.0/255.0
green:77.0/255.0
blue:141.0/255.0
alpha:1.0];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *tempUID = [uidArray objectAtIndex:indexPath.row];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:tempUCID forKey:#"corpUcid"];
[prefs setObject:#"PROFILER" forKey:#"selProfiler"];
CorpPrevFront *corpPrevFront = [[CorpPrevFront alloc]initWithNibName:#"CorpPrevFront" bundle:nil];
[self.navigationController pushViewController:corpPrevFront animated:NO];
[corpPrevFront release];
[tableView deselectRowAtIndexPath:indexPath animated:NO];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
//FOR VIEW
if (buttonIndex == 1 && [alertView tag] == 1) {
// IT WILL BE MATCH ON CorpPrevFront CLASS
}
//FOR DELETE
if(buttonIndex == 2 && [alertView tag] == 1){
} else if(buttonIndex == 1 && [alertView tag] == 2){
DeleteProfiler *delProfiler = [[DeleteProfiler alloc]init];
BOOL del = [delProfiler deleteProfiler:selectedCpUid];
//[delProfiler deleteProfiler:selectedCpUcid];
if (del == YES) {
[repArray removeObjectAtIndex:selectedIndexPath.section];
[businessArray removeObjectAtIndex:selectedIndexPath.row];
[titleArray removeObjectAtIndex:selectedIndexPath.row];
[ucidArray removeObjectAtIndex:selectedIndexPath.row];
[self.corporateTable reloadData];
}
}
}
I am trying to delete an array element from a method. If I execute the below line then the app crashes automatically in my iPod Touch. But it works fine in simulator without any errors.
[repArray removeObjectAtIndex:selectedIndexPath.row];
or
[repArray removeObjectAtIndex:0];
both crashes the app even if I have more than one elements in array.
When you app crashes like that, 99% of the time you are trying to remove an object beyond the bounds of array.

pushViewController:detail not pushing detailView

I had my app navigating views perfectly. Now, for some reason that I can't figure out, my detailView is not presenting on the pushViewController:detail method in my modal view.
I cannot figure out why it's not working any more. Any help would be appreciated. Thanks.
Here's the method:
- (void)tableView:(UITableView *)tView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tView deselectRowAtIndexPath:indexPath animated:YES];
if(indexPath.row == 0){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
if(indexPath.row == 1){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
if(indexPath.row == 2){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
if(indexPath.row == 3){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
if(indexPath.row == 4){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
}
Here's the class code. I'm not sure if I need to pass in a navigationController with modalView:
//
// ModalView.m
// DiningLog
//
// Created by Eric Rea on 10/10/11.
// Copyright 2011 Avid. All rights reserved.
//
#import "ModalView.h"
#import "DetailView.h"
#implementation ModalView
#synthesize tableView, excersizeName, numSets, time, restTime, dateFormatter, rating, excersizeArray, plistArray, numberWithBool;
-(IBAction) cancel:(id)sender{
[self dismissModalViewControllerAnimated:YES];
}
-(IBAction) save:(id)sender{
// get paths from root direcory
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
// get documents path
NSString *documentsPath = [paths objectAtIndex:0];
// get the path to our Data/plist file
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"ExcersizeList.plist"];
// check to see if Data.plist exists in documents
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath])
{
// if not in documents, get property list from main bundle
plistPath = [[NSBundle mainBundle] pathForResource:#"Excersizes" ofType:#"plist"];
}
// read property list into memory as an NSData object
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSString *errorDesc = nil;
NSPropertyListFormat format;
// convert static property list into dictionary object
NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization propertyListFromData:plistXML mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&errorDesc];
if (!temp)
{
NSLog(#"Error reading plist: %#, format: %d", errorDesc, format);
}
// assign values
self.plistArray = [NSMutableArray arrayWithArray:[temp objectForKey:#"Excersizes"]];
NSLog(#"The contents of plistArray is%#", plistArray);
// set the variables to the values in the text fields
self.excersizeArray = [[NSMutableArray alloc] initWithCapacity:4];
[excersizeArray addObject:excersizeName];
[excersizeArray addObject:numSets];
[excersizeArray addObject:time];
[excersizeArray addObject:restTime];
[plistArray addObject:excersizeArray];
// create dictionary with values in UITextFields
NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: plistArray, nil] forKeys:[NSArray arrayWithObjects: #"Excersizes", nil]];
NSString *error = nil;
// create NSData from dictionary
// NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
// check is plistData exists
if(plistDict)
{
// write plistData to our Data.plist file
[plistDict writeToFile:plistPath atomically:YES];
}
else
{
NSLog(#"Error in saveData: %#", error);
[error release];
}
[self dismissModalViewControllerAnimated:YES];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tView {
// Return the number of sections.
return 1;
}
-(void)setObject:(id)object forNum:(int)num{
if(num == 0){
self.excersizeName = object;
NSLog(#"res %#", self.excersizeName);
}else if(num == 1){
self.numSets = object;
NSLog(#"res %#", self.numSets);
}else if(num == 2){
self.time = object;
NSLog(#"res %#", self.time);
}else if(num == 3){
self.restTime = object;
NSLog(#"res %#", self.restTime);
}else if(num == 4){
self.rating = [object floatValue];
}
[tableView reloadData];
}
- (NSInteger)tableView:(UITableView *)tView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return 5;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:CellIdentifier] autorelease];
}
if(indexPath.row == 0){
cell.textLabel.text = #"Excersize";
cell.detailTextLabel.text = excersizeName;
}
if(indexPath.row == 1){
cell.textLabel.text = #"Sets";
cell.detailTextLabel.text = numSets;
}
if(indexPath.row == 2){
cell.textLabel.text = #"Time";
cell.detailTextLabel.text = time;
}
if(indexPath.row == 3){
cell.textLabel.text = #"Rest";
cell.detailTextLabel.text = restTime;
}
if(indexPath.row == 4){
cell.textLabel.text = #"Rating";
cell.detailTextLabel.text = [NSString stringWithFormat:#"%f",rating];
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
- (NSDateFormatter *)dateFormatter {
if (dateFormatter == nil) {
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
}
return dateFormatter;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tView deselectRowAtIndexPath:indexPath animated:YES];
if(indexPath.row == 0){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
if(indexPath.row == 1){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
if(indexPath.row == 2){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
if(indexPath.row == 3){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
if(indexPath.row == 4){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
}
// The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization.
}
return self;
}
*/
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
*/
/*
// 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 {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
#end
Have you debugged and checked that your navigationController isn't nil ?
I figured it out. I accidentally erased the method insertNewObject in my rootViewController. When I rewrote it, I forgot to add in ModalView * modal = [[ModalView alloc] init];. That was the problem.
Here's what the method looks like now that it's working:
- (void)insertNewObject {
ModalView * modal = [[ModalView alloc] init];
UINavigationController *controller = [[UINavigationController alloc] initWithRootViewController:modal];
[self presentModalViewController:controller animated:YES];
}