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

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

Related

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

UICollection View Deleting Section

I have searched a lot to find a solution to delete section's in a UICollectionView
but all the proposed solutions leading to a crash.
The code is I have used is:
[categoryCollection performBatchUpdates:^{
NSIndexSet *indexSet=[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, keys.count-1)];
[categoryCollection deleteSections:indexSet];
} completion:nil];
Update:
#implementation BooksLayout
- (void)prepareLayout {
// Registers my decoration views.
[self registerClass:[ShelfView class] forDecorationViewOfKind:[ShelfView kind]];
}
- (UICollectionViewLayoutAttributes *)layoutAttributesForDecorationViewOfKind:(NSString *)decorationViewKind atIndexPath:(NSIndexPath *)indexPath {
// Prepare some variables.
NSIndexPath *nextIndexPath = [NSIndexPath indexPathForItem:indexPath.row+1 inSection:indexPath.section];
UICollectionViewLayoutAttributes *cellAttributes = [self layoutAttributesForItemAtIndexPath:indexPath];
UICollectionViewLayoutAttributes *nextCellAttributes = [self layoutAttributesForItemAtIndexPath:nextIndexPath];
UICollectionViewLayoutAttributes *layoutAttributes = [UICollectionViewLayoutAttributes layoutAttributesForDecorationViewOfKind:decorationViewKind withIndexPath:indexPath];
CGRect baseFrame = cellAttributes.frame;
CGRect nextFrame = nextCellAttributes.frame;
CGFloat strokeWidth = 8;
CGFloat spaceToNextItem = 0;
if (nextFrame.origin.y == baseFrame.origin.y)
spaceToNextItem = (nextFrame.origin.x - baseFrame.origin.x - baseFrame.size.width);
// Positions the horizontal line for this item.
layoutAttributes.frame = CGRectMake(10,
baseFrame.origin.y + baseFrame.size.height,
300,
strokeWidth);
layoutAttributes.zIndex = 1;
return layoutAttributes;
}
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
NSArray *baseLayoutAttributes = [super layoutAttributesForElementsInRect:rect];
NSMutableArray * layoutAttributes = [baseLayoutAttributes mutableCopy];
for (UICollectionViewLayoutAttributes *thisLayoutItem in baseLayoutAttributes) {
if (thisLayoutItem.representedElementCategory == UICollectionElementCategoryCell) {
UICollectionViewLayoutAttributes *newHorizontalLayoutItem = [self layoutAttributesForDecorationViewOfKind:[ShelfView kind] atIndexPath:thisLayoutItem.indexPath];
[layoutAttributes addObject:newHorizontalLayoutItem];
}
}
return layoutAttributes;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
if([sortString isEqualToString:#"title"]){
NSArray *keys=[bookObj.orderedBooks allKeys];
keys = [keys sortedArrayUsingSelector:
#selector(localizedCaseInsensitiveCompare:)];
return [[bookObj.orderedBooks objectForKey:[keys objectAtIndex:section]] count];
}
else
return bookObj.booksArray.count;
}

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

prepareForSegue not passing correct PFFile

When passing a PFFile into new view I am either getting no image or the wrong image.
Here is prepareForSegue method
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"ShowWine"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
PFObject *object = [self.objects objectAtIndex:indexPath.row];
PFFile *file = [object objectForKey:#"image"];
[[segue destinationViewController] setFile:file];
}
}
And the rest of my relevant implementation file, I just think that I am not getting to the right row in the right section?
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return self.sections.allKeys.count;
}
- (NSString *)wineTypeForSection:(NSInteger)section {
return [self.sectionToWineTypeMap objectForKey:[NSNumber numberWithInt:section]];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSString *wineType = [self wineTypeForSection:section];
NSArray *rowIndecesInSection = [self.sections objectForKey:wineType]; return rowIndecesInSection.count;
}
- (void)objectsDidLoad:(NSError *)error {
[super objectsDidLoad:error];
[self.sections removeAllObjects];
[self.sectionToWineTypeMap removeAllObjects];
NSInteger section = 0;
NSInteger rowIndex = 0;
for (PFObject *object in self.objects) {
NSString *wineType = [object objectForKey:#"wineType"];
NSMutableArray *objectsInSection = [self.sections objectForKey:wineType];
if (!objectsInSection) {
objectsInSection = [NSMutableArray array];
[self.sectionToWineTypeMap setObject:wineType forKey:[NSNumber numberWithInt:section++]];
}
[objectsInSection addObject:[NSNumber numberWithInt:rowIndex++]];
[self.sections setObject:objectsInSection forKey:wineType];
}
}
- (PFObject *)objectAtIndexPath:(NSIndexPath *)indexPath {
NSString *wineType = [self wineTypeForSection:indexPath.section];
NSArray *rowIndecesInSection = [self.sections objectForKey:wineType];
NSNumber *rowIndex = [rowIndecesInSection objectAtIndex:indexPath.row];
return [self.objects objectAtIndex:[rowIndex intValue]];
}
What you should try doing is the following :
Create an instance variable (PFFile *aFile)
In didSelectRowAtIndexPath:, call your objectAtIndexPath: method, and set aFile with the returning value
Still in didSelectRowAtIndexPath:, call your performSegueWithIdentifier: and in prepareForSegue:, just set the destination file to your var : [[segue destinationViewController] setFile: aFile];.
Try this, and see if it works better. If not, please let me know !

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