My tableView methods have poor performance - objective-c

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...

Related

Hide the autocomplete Tableview when text field is empty

The following code will generate a custom autocomplete Table View autocompleteTableView below my text field txtActivity. How do I hide the Table View when text field is empty.
- (void)viewDidLoad
{
[super viewDidLoad];
self.txtActivity.delegate = self;
[self cofigureAutoComTableView];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)rangereplacementString:(NSString *)string
{
autocompleteTableView.hidden = NO;
NSString *substring = [NSString stringWithString:textField.text];
substring = [substring stringByReplacingCharactersInRange:range withString:string];
[self searchAutocompleteEntriesWithSubstring:substring];
return YES;
}
- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring
{
autocompleteMArray = [[NSMutableArray alloc] init];
[autocompleteMArray removeAllObjects];
for(NSString *curString in sCategory) { //**** sCategory is a mutable array generated in another method not shown ****
NSRange substringRange = [curString rangeOfString:substring];
if (substringRange.length > 0) {
[autocompleteMArray addObject:curString];
}
}
NSLog(#"*******The autocompleteMArray : %# ", autocompleteMArray);
[autocompleteTableView reloadData];
}
-(void)cofigureAutoComTableView
{
autocompleteTableView = [[UITableView alloc] initWithFrame:CGRectMake(self.txtActivity.frame.origin.x-10,self.txtActivity.frame.origin.y+32,self.txtActivity.frame.size.width, 120) style:UITableViewStylePlain];
autocompleteTableView.delegate = self;
autocompleteTableView.dataSource = self; //**** Setting this to self, is it correct???
autocompleteTableView.scrollEnabled = YES;
autocompleteTableView.hidden = YES;
[self.view addSubview:autocompleteTableView];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return autocompleteMArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"cellIdentifier";
UITableViewCell *cell = [self.autocompleteTableView dequeueReusableCellWithIdentifier:cellIdentifier];
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
cell.textLabel.text = [autocompleteMArray objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath (NSIndexPath *)indexPath;
{
//**** NOT DETECTING *******
NSLog(#"Selected Cell %#", [autocompleteMArray objectAtIndex:indexPath.row]);
}
If substringRange length is 0 then assign sCategory array to autocompleteMArray and reload the tableview.
- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring
{
autocompleteMArray = [[NSMutableArray alloc] init];
[autocompleteMArray removeAllObjects];
if ([substring length] == 0)
{
for(NSString *curString in sCategory)
{ //**** sCategory is a mutable array generated in another method not shown ****
NSRange substringRange = [curString rangeOfString:substring];
if (substringRange.length > 0)
{
[autocompleteMArray addObject:curString];
}
}
}
else
{
autocompleteMArray = sCategory;
}
NSLog(#"*******The autocompleteMArray : %# ", autocompleteMArray);
[autocompleteTableView reloadData];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if([[NSString stringWithFormat:#"%#%#",textField.text,string] isEqualToString:#""]) {
autocompleteTableView.hidden = YES;
} else {
autocompleteTableView.hidden = range.location == 0 ? YES : NO;
NSString *substring = [NSString stringWithString:textField.text];
substring = [substring stringByReplacingCharactersInRange:range withString:string];
[self searchAutocompleteEntriesWithSubstring:substring];
}
return YES; }

Array is deleting the last object in Xcode

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.

iOS search bar issue

I am searching the table view data. Tableview contains contact list and when I give the contact name it's not able to give search bar result. Here is my code:
- (void)viewDidLoad
{
[super viewDidLoad];
// Hide the search bar until user scrolls up
CGRect newBounds = [[self tableview] bounds];
newBounds.origin.y = newBounds.origin.y + search.bounds.size.height;
[[self tableview] setBounds:newBounds];
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(goToSearch)];
self.navigationItem.rightBarButtonItem=doneButton;
self.filtereditems=[NSMutableArray arrayWithCapacity:[array count]];
[self loadPhoneContacts];
[[self tableview] reloadData];
}
- (void)goToSearch
{
[search becomeFirstResponder];
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString
{
// Tells the table data source to reload when text changes
[self filterContentForSearchText:searchString scope:
[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:
[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
// Return YES to cause the search result table view to be reloaded.
return YES;
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchScope:(NSInteger)searchOption
{
// Tells the table data source to reload when scope bar selection changes
[self filterContentForSearchText:[self.searchDisplayController.searchBar text] scope:
[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]];
// Return YES to cause the search result table view to be reloaded.
return YES;
}
-(void)loadPhoneContacts{
ABAuthorizationStatus status = ABAddressBookGetAuthorizationStatus();
if (status == kABAuthorizationStatusDenied) {
[[[UIAlertView alloc] initWithTitle:nil message:#"This app requires access to your contacts to function properly. Please visit to the \"Privacy\" section in the iPhone
Settings app." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil] show];
return;
}
CFErrorRef error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
if (error) {
NSLog(#"ABAddressBookCreateWithOptions error: %#", CFBridgingRelease(error));
if (addressBook) CFRelease(addressBook);
return;
}
if (status == kABAuthorizationStatusNotDetermined)
{
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
if (error) {
NSLog(#"ABAddressBookRequestAccessWithCompletion error: %#",
CFBridgingRelease(error));
}
if (granted) {
// if they gave you permission, then just carry on
[self listPeopleInAddressBook:addressBook];
} else {
dispatch_async(dispatch_get_main_queue(), ^{
[[[UIAlertView alloc] initWithTitle:nil message:#"This app requires access to
your contacts to function properly. Please visit to the \"Privacy\" section in the iPhone
Settings app." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil] show];
});
}
if (addressBook) CFRelease(addressBook);
});
} else if (status == kABAuthorizationStatusAuthorized) {
[self listPeopleInAddressBook:addressBook];
if (addressBook) CFRelease(addressBook);
}
}
- (void)listPeopleInAddressBook:(ABAddressBookRef)addressBook
{
NSInteger numberOfPeople = ABAddressBookGetPersonCount(addressBook);
NSMutableArray * contactList=
CFBridgingRelease(ABAddressBookCopyArrayOfAllPeople(addressBook));
array =[[NSMutableArray alloc] init];
for (int i = 0; i < numberOfPeople; i++)
{
ABRecordRef person = (__bridge ABRecordRef)contactList[i];
firstName = CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNameProperty));
lastName = CFBridgingRelease(ABRecordCopyValue(person, kABPersonLastNameProperty));
NSLog(#"Name:%# %#", firstName, lastName);
ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
CFIndex numberOfPhoneNumbers = ABMultiValueGetCount(phoneNumbers);
for (CFIndex i = 0; i < numberOfPhoneNumbers; i++)
{
phoneNumber = CFBridgingRelease(ABMultiValueCopyValueAtIndex(phoneNumbers, i));
NSLog(#" phone is:%#", phoneNumber);
}
[array addObject:[NSDictionary dictionaryWithObjectsAndKeys:firstName , #"first_name"
, lastName , #"last_name" ,phoneNumber,#"phone_Number" ,nil]];
NSArray *ar=[[NSArray alloc]init];
NSLog(#"array is,%#",ar);
CFRelease(phoneNumbers);
}
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath
*)indexPath
{
return 50;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.searchDisplayController.searchResultsTableView)
return [filtereditems count];
else
return [array count];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath
{
NSLog(#"array is %#",array);
static NSString *CustomCellID = #"cell";
contactcellTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CustomCellID];
if (cell == nil)
{
cell=[[contactcellTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CustomCellID];
NSArray *nib=[[NSBundle mainBundle]loadNibNamed:#"contactcellTableViewCell" owner:self
options:nil];
cell =[nib objectAtIndex:0];
}
if (tableView == self.searchDisplayController.searchResultsTableView) {
cell.Firstnamelbl.text = [filtereditems objectAtIndex:indexPath.row];
cell.Lastnamelbl.text = [filtereditems objectAtIndex:indexPath.row];
} else {
cell.Firstnamelbl.text = [[array
objectAtIndex:indexPath.row]objectForKey:#"first_name"];
cell.Lastnamelbl.text = [[array objectAtIndex:indexPath.row]objectForKey:#"last_name"];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath
*)indexPath
{
[array removeAllObjects];
contactcellTableViewCell *cell = (contactcellTableViewCell *) [tableView
cellForRowAtIndexPath:indexPath];
static NSString *CustomCellID = #"cell";
NSString *string=[firstName stringByAppendingString:lastName];
if (cell == nil)
{
cell=[[contactcellTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CustomCellID];
NSArray *nib=[[NSBundle mainBundle]loadNibNamed:#"contactcellTableViewCell" owner:self
options:nil];
cell =[nib objectAtIndex:0];
}
if (cell.m_checkImageView.image == [UIImage imageNamed:#"Selected.png"])
{
cell.m_checkImageView.image = [UIImage imageNamed:#"Unselected.png"];
}
else
{
cell.m_checkImageView.image = [UIImage imageNamed:#"Selected.png"];
NSLog(#"string is %#",string);
}
}
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
[self.filtereditems removeAllObjects];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF.name contains[c]
%#",searchText];
NSArray *tempArray = [array filteredArrayUsingPredicate:predicate];
if(![scope isEqualToString:#"All"]) {
// Further filter the array with the scope
NSPredicate *scopePredicate = [NSPredicate predicateWithFormat:#"SELF.category
contains[c] %#",scope];
tempArray = [tempArray filteredArrayUsingPredicate:scopePredicate];
}
filtereditems = [NSMutableArray arrayWithArray:tempArray];
}
here is my code and when i am yping any thing in the search bar i cannot able o find the search thing and search bar is not responding at all. please help thanks in advance

How to get Full path of selected Node in NSOutlineView + NSTreeController

I have referred NSOutlineview from this link. I dynamically load all values as based on selected values. Here i struct a issue while getting paths.
Like, Folder path. (eg.: D:/NewFolder/Test/blah/blah1
In same I need to get the full path selected child from parent. In the image, i selected
Project. so I need the path should be get like as follows,
/Test/New Folder/Untitled/Project
My code is
- (IBAction) ButtonClick:(id)sender
{
self.treeoutlineview.delegate = self;
self.treeoutlineview.dataSource = self;
NSString *roots = #"/";
NSIndexPath *indexPath = nil;
indexPath = [NSIndexPath indexPathWithIndex:[contents count]];
TreeNode *node = [[TreeNode alloc] init];
[node TitleSet:roots];
[self.treeController insertObject:node atArrangedObjectIndexPath:indexPath];
}
- (id)outlineView:(NSOutlineView *)outlineView child:(NSInteger)index ofItem:(id)item {
childItem = item;
return childItem;
}
- (NSInteger)outlineView:(NSOutlineView *)outlineView numberOfChildrenOfItem:(id)item {
noofchildren = 0;
return noofchildren;
}
- (BOOL)outlineView:(NSOutlineView *)outlineView isItemExpandable:(id)item {
return YES;
}
- (id)outlineView:(NSOutlineView *)outlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item {
valueforcolumn = nil;
}
- (BOOL)outlineView:(NSOutlineView *)ov shouldSelectItem:(id)item {
{
rec = #"New Folder|Test|Backup|Project";
NSArray *arr = [rec componentsSeparatedByString:#"|"];
[loadChildValues removeAllObjects];
NSIndexPath *indexPath = nil;
if (![self.treeController selectionIndexPath])
{
indexPath = [NSIndexPath indexPathWithIndex:[contents count]];
}
else
{
if ([[[self.treeController selectedObjects] objectAtIndex:0] isLeaf])
{
NSBeep();
return;
}
indexPath = [self.treeController selectionIndexPath];
indexPath = [indexPath indexPathByAddingIndex:[[[[self.treeController selectedObjects] objectAtIndex:0] children] count]];
}
for (int i = 2; i< [arr count]; i++) {
[loadChildValues addObject:[arr objectAtIndex:i]];
TreeNode *node = [[TreeNode alloc] init];
[node TitleSet:[arr objectAtIndex:i]];
[self.treeController insertObject:node atArrangedObjectIndexPath:indexPath];
}
}
How i do this. Any body pls help to resolve this. Thanks in Advance.
I did it. I have did the following code. any one need, use this code.
In first step u need to get Indexpath of item
- (IBAction)RefreshTree:(id)sender {
NSIndexPath *indexPath = nil;
if (![self.treeController selectionIndexPath]) {
indexPath = [NSIndexPath indexPathWithIndex:[contents count]];
}
else {
if ([[[self.treeController selectedObjects] objectAtIndex:0] isLeaf]) {
NSBeep();
NSIndexPath *selectedfiler_indexPath = [[[self.treeController selectedNodes] objectAtIndex:0] indexPath];
[self selectValue:selectedfiler_indexPath];
}
else
{
indexPath = [self.treeController selectionIndexPath];
[self selectValue:indexPath];
}
}
}
- (void) selectValue : (NSIndexPath *) indexpath
{
NSMutableArray *dummyval = [[NSMutableArray alloc] init];
NSTreeNode *firstSelectedNode = [[self.treeController selectedNodes] objectAtIndex:0];
NSString *getsel = [firstSelectedNode representedObject];
[dummyval addObject:getsel];
int i = 0;
NSInteger j = [[firstSelectedNode indexPath]length];
while (i < j) {
firstSelectedNode = [firstSelectedNode parentNode];
if (i < j -1)
{
NSString *st = [firstSelectedNode representedObject];
[dummyval addObject:[NSString stringWithFormat:#"%#",st]];
}
i++;
}
NSArray *reversedArray = [[dummyval reverseObjectEnumerator] allObjects];
NSString *ret_path=[reversedArray componentsJoinedByString:#"/"];
ret_path = [ret_path substringWithRange:NSMakeRange(1, [ret_path length] - 1)];
NSLog("%#",ret_path);
}
Output is : Test/New Folder/Untitled/Project

iOS UITableView with 10,000 record SQLLite DB

My iOS app populates an SQLlite database (using FMDB) from a web query. There is a UITableView to display this data. Since I started writing the app the size of this db has exploded to about 10,000 records.
My current design is to load the data in an array from the db and then use that in the UITableView. It works, and I have the alphabetized index on the right hand side of the screen for the user to quickly access the data.
The problem of course is it takes 15-20 seconds to load the array. I originally designed this to load every time the user hits the UITableView, but that means 15-20 seconds every time.
Is there a way to only load some of the data in the UITableView while keeping the search functionality and the index?
Can/should I load the array once and reuse it? I have tried but I can't seem to get that work.
As a last resort, I could switch to CoreData but I really don't want to switch horses in midstream.
UITableView implementation:
#import "ContactViewController.h"
#import "ContactDetailViewController.h"
#interface ContactViewController ()
#end
#implementation ContactViewController {
NSMutableArray *_contacts;
UISearchDisplayController *searchController;
BOOL isSearching;
}
- (void)awakeFromNib {
if ([[UIDevice currentDevice] userInterfaceIdiom] ==
UIUserInterfaceIdiomPad) {
self.clearsSelectionOnViewWillAppear = NO;
self.preferredContentSize = CGSizeMake(320.0, 600.0);
}
[super awakeFromNib];
}
- (void)viewDidLoad {
[super viewDidLoad];
// Get array of employees and sections
_contacts = [ContactsDatabase getContacts];
self.sections = [ContactsDatabase getSections:_contacts];
// Set up Search
self.searchDisplayController.displaysSearchBarInNavigationBar = YES;
self.filteredContacts = [NSMutableArray array];
searchController.delegate = self;
searchController.searchResultsDataSource = self;
isSearching = FALSE;
// iPad
// self.dtailViewController = (detailViewController
// *)[[self.splitViewController.viewControllers lastObject]
// topViewController];
// Set the back bar button
UIBarButtonItem *backButton =
[[UIBarButtonItem alloc] initWithTitle:#"Contacts"
style:UIBarButtonItemStylePlain
target:nil
action:nil];
self.navigationItem.backBarButtonItem = backButton;
}
#pragma mark - Table View
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
NSInteger tmpRows;
if (tableView == self.searchDisplayController.searchResultsTableView) {
tmpRows = [self.filteredContacts count];
} else {
tmpRows = [[self.sections
valueForKey:[[[self.sections allKeys]
sortedArrayUsingSelector:
#selector(localizedCaseInsensitiveCompare:)]
objectAtIndex:section]] count];
}
return tmpRows;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell =
[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
}
if (isSearching) {
contact *thisContact = [self.filteredContacts objectAtIndex:indexPath.row];
cell.textLabel.text = thisContact.cmpNme;
} else {
contact *thisContact = [[self.sections
valueForKey:[[[self.sections allKeys]
sortedArrayUsingSelector:
#selector(localizedCaseInsensitiveCompare:)]
objectAtIndex:indexPath.section]]
objectAtIndex:indexPath.row];
cell.textLabel.text = thisContact.cmpNme;
}
return cell;
}
#pragma mark - Table Sections
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
NSInteger tmpCount;
if (isSearching) {
tmpCount = 1;
} else {
tmpCount = [[self.sections allKeys] count];
}
return tmpCount;
}
- (NSString *)tableView:(UITableView *)tableView
titleForHeaderInSection:(NSInteger)section {
NSString *tmpString;
if (tableView == self.searchDisplayController.searchResultsTableView) {
tmpString = nil;
} else {
tmpString = [[[self.sections allKeys]
sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)]
objectAtIndex:section];
}
return tmpString;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"showContactDetail"]) {
contact *dtlContact;
if (isSearching) {
dtlContact = [self.filteredContacts
objectAtIndex:self.searchDisplayController.searchResultsTableView
.indexPathForSelectedRow.row];
} else {
dtlContact = [[self.sections
valueForKey:[[[self.sections allKeys]
sortedArrayUsingSelector:
#selector(localizedCaseInsensitiveCompare:)]
objectAtIndex:[self.tableView indexPathForSelectedRow]
.section]]
objectAtIndex:[self.tableView indexPathForSelectedRow].row];
}
self.contactDetailViewController.detailItem = dtlContact;
[[segue destinationViewController] setDetailItem:dtlContact];
}
}
#pragma mark - Right side bar alphabetical index
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
NSArray *tmpTitle;
if (isSearching) {
tmpTitle = nil;
} else {
tmpTitle = [[self.sections allKeys]
sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
}
return tmpTitle;
}
#pragma mark - Search methods
- (void)searchDisplayControllerWillBeginSearch:
(UISearchDisplayController *)controller {
isSearching = TRUE;
self.searchDisplayController.searchBar.showsCancelButton = YES;
[self.tableView reloadSectionIndexTitles];
}
- (void)searchDisplayControllerDidEndSearch:
(UISearchDisplayController *)controller {
isSearching = FALSE;
self.searchDisplayController.searchBar.showsCancelButton = NO;
[self.tableView reloadSectionIndexTitles];
}
- (void)filterContentForSearchText:(NSString *)searchText
scope:(NSString *)scope {
[self.filteredContacts removeAllObjects];
NSPredicate *predicate =
[NSPredicate predicateWithFormat:#"cmpNme contains[c] %#", searchText];
NSArray *tempArray = [_contacts filteredArrayUsingPredicate:predicate];
// Move to filtered array
self.filteredContacts = [NSMutableArray arrayWithArray:tempArray];
self.sections = [ContactsDatabase getSections:_contacts];
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString {
isSearching = TRUE;
[self
filterContentForSearchText:searchString
scope:[self.searchDisplayController.searchBar
.scopeButtonTitles
objectAtIndex:
self.searchDisplayController.searchBar
.selectedScopeButtonIndex]];
return YES;
}
#end
getContacts methods
+ (NSMutableArray *)getContacts {
id tmpDatabasePath = [(AppDelegate *)
[[UIApplication sharedApplication] delegate] databasePathContacts];
NSMutableArray *tmpContacts;
tmpContacts = [[NSMutableArray alloc] init];
FMDatabase *db = [FMDatabase databaseWithPath:tmpDatabasePath];
[db open];
FMResultSet *results =
[db executeQuery:#"SELECT * FROM contacts ORDER by cmpNme"];
while ([results next]) {
contact *thisContact = [contact new];
thisContact.cmpNme = [results stringForColumn:#"cmpNme"];
thisContact.fstNme = [results stringForColumn:#"fstNme"];
thisContact.lstNme = [results stringForColumn:#"lstNme"];
thisContact.cntTyp = [results stringForColumn:#"cnttyp"];
NSString *tst = [results stringForColumn:#"phnNbr"];
thisContact.phnNbr = [NSNumber numberWithInt:[tst intValue]];
thisContact.adr1 = [results stringForColumn:#"adr1"];
thisContact.adr2 = [results stringForColumn:#"adr2"];
thisContact.cty = [results stringForColumn:#"cty"];
thisContact.ste = [results stringForColumn:#"ste"];
tst = [results stringForColumn:#"zip"];
thisContact.zip = [NSNumber numberWithInt:[tst intValue]];
thisContact.ema = [results stringForColumn:#"ema"];
tst = [results stringForColumn:#"id"];
thisContact.id = [NSNumber numberWithInt:[tst intValue]];
[tmpContacts addObject:thisContact];
}
[db close];
return tmpCon