Reducing the length of a long for/if statement - objective-c

I'm currently trying to make the code of an app I'm developing a bit more efficient and easier to read. Basically what this does is retrieve an array from NSUserDefaults of player names, and fills in the 6 text boxes (tagged 6-11) with these names. If there isn't an existing array it'll use another set of names. Any ideas for simplifying this code would be appreciated.
if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
NSMutableArray *names = [[NSMutableArray alloc] initWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:#"nameArray"]];
for (int i = 0; i <= 5; i++) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
UITableViewCell *cell = [playerTable cellForRowAtIndexPath:indexPath];
for (UIView *view in cell.contentView.subviews) {
if ([view isKindOfClass:[UITextField class]]) {
UITextField *txtField = (UITextField *)view;
if (txtField.tag == 6) {
if([[NSUserDefaults standardUserDefaults] boolForKey:#"customNames"]) {
txtField.text = [names objectAtIndex:0]; }
else {
txtField.text = #"Peter";
}
}
if (txtField.tag == 7) {
if([[NSUserDefaults standardUserDefaults] boolForKey:#"customNames"]) {
txtField.text = [names objectAtIndex:1]; }
else {
txtField.text = #"Julia";
}
}
if (txtField.tag == 8) {
if([[NSUserDefaults standardUserDefaults] boolForKey:#"customNames"]) {
txtField.text = [names objectAtIndex:2]; }
else {
txtField.text = #"Durgan";
}
}
if (txtField.tag == 9) {
if([[NSUserDefaults standardUserDefaults] boolForKey:#"customNames"]) {
txtField.text = [names objectAtIndex:3]; }
else {
txtField.text = #"Bob";
}
}
if (txtField.tag == 10) {
if([[NSUserDefaults standardUserDefaults] boolForKey:#"customNames"]) {
txtField.text = [names objectAtIndex:4]; }
else {
txtField.text = #"Iseland";
}
}
if (txtField.tag == 11) {
if([[NSUserDefaults standardUserDefaults] boolForKey:#"customNames"]) {
txtField.text = [names objectAtIndex:5]; }
else {
txtField.text = #"Player";
}
}
}
}
}
[self saveNames];
}

Your could do this:
NSArray *defaultNames = #[#"Peter", #"Julia",...];
int offsetIndex = 6;
BOOl needCustomNames = [[NSUserDefaults standardUserDefaults] boolForKey:#"customNames"];
for (UIView *view in cell.contentView.subviews)
{
if ([view isKindOfClass:[UITextField class]])
{
UITextField *txtField = (UITextField *)view;
int index = [txtField tag]-offsetIndex;
if (tag >= 6 && tag <= 11)
{
if (needCustomNames)
textField.text = [names objectAtIndex:index];
else
textField.text = [defaultNames objectAtIndex:index];
}
}
}
For example, you called too many times the same lines in the for loop, like checking if you need to use or not a custom names (NSUserDefaults line).
I use an NSArray for the custom names to mimic the same logic, and used an offset to clarify it.

I would recommend to analyse your Code for redundance and exclude them in separate methods. so you have to call only the extern method than every code-party again and again.

Related

How to get other array value after NSCaseInsensitiveSearch

I have a question here. In textDidChange function, i have NSMutableArray _setItem2 with "name","image","price" columns. And in this case, I able to search by "Name" column via sample code as below.
However, i would like to present my other columns value such as price and image after search filtering. How can i do that? Please help.
-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
{
if(text.length == 0)
{
isFiltered = FALSE;
[searchBar resignFirstResponder];
}
else
{
isFiltered = true;
filteredTableData = [[NSMutableArray alloc] init];
for (NSDictionary *item in _setItem2) {
NSString *name = [item objectForKey:#"name"];
NSRange nameRange = [name rangeOfString:text options:NSCaseInsensitiveSearch];
if (nameRange.location != NSNotFound) {
[filteredTableData addObject:name];
}
}
}
[self.collectionView reloadData];
}
And here is my cellForItemAtIndexPath function
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
DCListGridCell *cell = nil;
cell = (_isSwitchGrid) ? [collectionView dequeueReusableCellWithReuseIdentifier:DCListGridCellID forIndexPath:indexPath] : [collectionView dequeueReusableCellWithReuseIdentifier:DCSwitchGridCellID forIndexPath:indexPath];
if(isFiltered)
{
NSString *str1 = [filteredTableData objectAtIndex:indexPath.row];
//HOW CAN I SHOW IMAGE AND PRICE HERE??? NOW THE VALUE IS WRONG
//==============================================================
//cell.productImage = [[_setItem2 objectAtIndex:indexPath.row] image];
cell.productName = [filteredTableData objectAtIndex:indexPath.row];
//cell.productPrice = [[_setItem2 objectAtIndex:indexPath.row] price];
}
else
{
cell.productImage = [_setItem[indexPath.row]valueForKey:#"image"];
cell.productName = [_setItem[indexPath.row]valueForKey:#"name"];
cell.productPrice = [_setItem[indexPath.row]valueForKey:#"price"];
}
return cell;
}

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

UITableView values don't match its key form plist

I am making a plist viewer and editor for iOS, but the problem I have it, that the values don't match to its key. Like I have this plist
{
BuildMachineOSBuild = 12C54;
CAProcessCanAccessGPU = 1;
CFBundleAllowMixedLocalizations = 1;
CFBundleDevelopmentRegion = English;
CFBundleDisplayName = iAd;
CFBundleExecutable = AdSheet;
CFBundleIconFiles = (
"iAd.png",
"iAd#2x.png"
);
CFBundleIcons = {
CFBundlePrimaryIcon = {
CFBundleIconFiles = (
"iAd.png",
"iAd#2x.png"
);
UIPrerenderedIcon = 0;
};
};
CFBundleIdentifier = "com.apple.AdSheetPhone";
CFBundleInfoDictionaryVersion = "6.0";
CFBundleName = AdSheet;
CFBundlePackageType = APPL;
CFBundleResourceSpecification = "ResourceRules.plist";
CFBundleShortVersionString = "1.0";
CFBundleSignature = "????";
CFBundleSupportedPlatforms = (
iPhoneOS
);
CFBundleVersion = "1.0";
CLSystemService = 1;
CLVisibleImmediately = 1;
CanInheritApplicationStateFromOtherProcesses = 1;
DTCompiler = "com.apple.compilers.llvm.clang.1_0";
DTPlatformBuild = "";
DTPlatformName = iphoneos;
DTPlatformVersion = "7.0";
DTSDKBuild = 11A450;
DTSDKName = "iphoneos7.0.internal";
DTXcode = 0500;
DTXcodeBuild = 5A1344i;
MinimumOSVersion = "7.0";
NSPrincipalClass = ADSApplication;
SBAppTags = (
hidden
);
SBMachServices = (
"com.apple.AdSheetPhone.server",
"com.apple.AdSheetPhone.management",
"com.apple.uikit.viewservice.com.apple.AdSheetPhone"
);
UIBackgroundModes = (
continuous
);
UIDeviceFamily = (
1,
2
);
UIShouldIgnoreRemoteControlEvents = 1;
UIStatusBarHidden = 1;
UISupportedInterfaceOrientations = (
UIInterfaceOrientationPortrait,
UIInterfaceOrientationPortraitUpsideDown,
UIInterfaceOrientationLandscapeLeft,
UIInterfaceOrientationLandscapeRight
);
UIViewServiceUsesNSXPCConnection = 1;
}
)
I try to display the value and its key (or Dictionary for Dictionaries, Array for Arrays and Bool for Bools)
Then for example CanInheritApplicationStateFromOtherProcesses should show a 1 (wich is a BOOL), but is don't show any value. And CanInheritApplicationStateFromOtherProcesses is on index 0 of my UITableView, but it is on index 19 of the plist. Does anyone know how to fix this error. I am displaying the key in the cell.textLabel.text and the value in cell.detailTextLabel.text. Here is my code of - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"plist Cell" forIndexPath:indexPath];
id obj;
cell.textLabel.adjustsFontSizeToFitWidth = YES;
cell.detailTextLabel.minimumScaleFactor = 0.5;
cell.textLabel.font = [UIFont systemFontOfSize:14];
cell.detailTextLabel.font = [UIFont systemFontOfSize:13];
cell.editingAccessoryType = UITableViewCellEditingStyleNone;
if (self.plistDict) {
NSString* key = [[self.plistDict allKeys] objectAtIndex:indexPath.row];
cell.textLabel.text = key;
obj = [self.plistDict objectForKey:key];
} else {
cell.textLabel.text = [NSString stringWithFormat:#"%li", (long)indexPath.row];
obj = [self.plistArray objectAtIndex:indexPath.row];
}
if(([obj isKindOfClass:[NSArray class]] || [obj isKindOfClass:[NSMutableArray class]]) && cell.tag == 0){
cell.detailTextLabel.text = NSLocalizedString(#"Array", nil);
cell.tag = 1;
return cell;
} if(([obj isKindOfClass:[NSDictionary class]] || [obj isKindOfClass:[NSMutableDictionary class]]) && cell.tag == 0){
cell.detailTextLabel.text = NSLocalizedString(#"Dictionary", nil);
cell.tag = 2;
return cell;
} if ([obj isKindOfClass:[NSString class]] && cell.tag == 0) {
cell.detailTextLabel.text = [NSString stringWithFormat:#"%#", (NSString *)obj];
cell.tag = 3;
return cell;
} if ([obj isKindOfClass:[NSNumber class]]) {
if ([obj isKindOfClass:[#(YES) class]] && cell.tag == 0) {
[boolSwitch setOn:(BOOL)obj animated:YES];
[cell.contentView addSubview:boolSwitch];
cell.detailTextLabel.textColor = [UIColor clearColor];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.tag = 7;
return cell;
} else if (![obj isKindOfClass:[#(YES) class]] && cell.tag == 0) {
cell.detailTextLabel.text = [NSString stringWithFormat:#"%#", (NSNumber *)obj];
cell.tag = 4;
return cell;
} else {
return cell;
}
} if ([obj isKindOfClass:[NSData class]] && cell.tag == 0) {
cell.detailTextLabel.text = NSLocalizedString(#"Data", nil);
cell.tag = 5;
return cell;
} if ([obj isKindOfClass:[NSDate class]] && cell.tag == 0) {
cell.detailTextLabel.text = [NSString stringWithFormat:#"%#", (NSDate *)obj];
cell.tag = 6;
return cell;
} else {
return cell;
}
The odd thing is for the most keys the value matches, but not for all.
cell will be reused with tag. so you maybe should reset the tag before reuse the cell:
//CustomeCell.m
- (void)prepareForReuse{
[super prepareForReuse];
self.tag = 0;
}
Or in tableView delegate class:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
cell.tag = 0;
}

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