Remove all items from indexPathsForSelectedItems, UICollectionView - iphone

How to remove all the items from indexPathSelectdItems. Below is my code I am using to save values to array from indexPathSelectedITems, but need to clear the array when section changes and array should save value as a fresh. But indexPathForSelectedItems add previousSelectedValues also.
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
NSString *seatV;
int cs;
NSString *secVal = [arrSeatSel objectAtIndex:indexPath.section];
NSArray *arrSplit = [secVal componentsSeparatedByString:#":"];
seatV = [arrSplit objectAtIndex:1];
cs = [seatV integerValue];
int v;
NSString *cnt = [NSString stringWithFormat:#"%#",[arrTot objectAtIndex:indexPath.section]];
v = [cnt intValue];
NSString *sect = [NSString stringWithFormat:#"%d", indexPath.section];
if(indexPath.item < v)
{
if([sectionInfo count] < cs)
{
itemPaths = [self.collectionView indexPathsForSelectedItems];
//NSMutableArray *array = [NSMutableArray array];
//array = [self.collectionView indexPathsForSelectedItems];
//sectionInfo = [self.collectionView indexPathsForSelectedItems];
sectionInfo = [NSMutableArray arrayWithArray: [self.collectionView indexPathsForSelectedItems]];
//[sectionInfo addObject:[[self.collectionView indexPathsForSelectedItems] lastObject]];
[selectedItemsInfo setObject:sectionInfo forKey:sect];
cell=[self.collectionView cellForItemAtIndexPath:indexPath];
cell.contentView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"yellow_seat.png"]];
//sectionInfo1 = sectionInfo;
}
else
{
[self.collectionView deselectItemAtIndexPath:[NSIndexPath indexPathForItem:indexPath.row inSection:indexPath.section] animated:YES];
[sectionInfo1 addObject:[selectedItemsInfo objectForKey:sect]];
[selectedItemsInfo setObject:sectionInfo1 forKey:sect];
[sectionInfo removeAllObjects];
}
}
else
{
[self.collectionView deselectItemAtIndexPath:[NSIndexPath indexPathForItem:indexPath.row inSection:indexPath.section] animated:YES];
}
NSLog(#"section array:%#", sectionInfo);
NSLog(#"section array1:%#", sectionInfo1);
NSLog(#"selected seats dict:%#", selectedItemsInfo);
}
So, how to clear previous values indexPathSelectedItems so that it can hold new selected values only?

Try using this code as per your requirement.
[self deleteItemsFromDataSourceAtIndexPaths:selectedItemsIndexPaths];
OR
[self.collectionView deleteItemsAtIndexPaths:selectedItemsIndexPaths];

Related

indexing not working in tableview

i am trying to achieve indexing on table for that i use following method indexing appears on right side but it is not working code is below
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 2;
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
NSArray *toBeReturned = [NSArray arrayWithArray:
[#"A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|#"
componentsSeparatedByString:#"|"]];
return toBeReturned;
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
int foundIndex = 0;
for (int i = 0; i< [mainArray count]; i++) {
// Here you return the name i.e. Honda,Mazda
// and match the title for first letter of name
// and move to that row corresponding to that indexpath as below
NSString *letterString = [[[mainArray valueForKey:#"name"] objectAtIndex:i] substringToIndex:1];
NSLog(#"letterString%#",letterString);
NSLog(#"title%#",title);
if ([[letterString uppercaseString ] compare:title] == NSOrderedDescending){
break;
foundIndex++; }
if(foundIndex > mainArray.count)
foundIndex = mainArray.count;
[table scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:foundIndex inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
return 1;
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 120;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
//—set the text to display for the cell—
NSLog(#"%d",mainArray.count);
NSLog(#"%#",mainArray);
UIImageView *selectionView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 768, 120)];
UIImage *image = [UIImage imageNamed:#"default.png"];
UIImageView* blockView = [[UIImageView alloc] initWithImage:image];
blockView.layer.cornerRadius = 4;
blockView.layer.masksToBounds = YES;
blockView.layer.borderWidth = 2;
blockView.layer.borderColor = [UIColor blackColor].CGColor;
blockView.frame = CGRectMake(5, 5, 110, 110);
// title isKindOfClass:[NSNull class]])
//NSLog(#"%#",[[mainArray valueForKey:#"image"] objectAtIndex:[indexPath row]]);
id obj = [[mainArray valueForKey:#"image"] objectAtIndex:[indexPath row]];
if ([obj isKindOfClass:[NSString class]])
{
[selectionView addSubview:blockView];
}
else {
UIImage *contactImage = [[UIImage alloc]init];
contactImage = [[mainArray valueForKey:#"image"] objectAtIndex:[indexPath row]];
// NSLog(#" array%#",[[mainArray valueForKey:#"image"] objectAtIndex:[indexPath row]]);
NSLog(#" image%#",contactImage);
UIImageView *blockView = [[UIImageView alloc] initWithImage:contactImage];
blockView.frame = CGRectMake(5, 5, 110, 110);
blockView.layer.cornerRadius = 4;
blockView.layer.masksToBounds = YES;
blockView.layer.borderWidth = 2;
blockView.layer.borderColor = [UIColor blackColor].CGColor;
[selectionView addSubview:blockView];
}
NSLog(#" name :%#",[[mainArray valueForKey:#"name"] objectAtIndex:[indexPath row]]);
if ([[[mainArray valueForKey:#"name"] objectAtIndex:[indexPath row]] isEqualToString:#"(null)"]) {
UILabel *name = [[UILabel alloc]initWithFrame:CGRectMake(130, 10, 310, 55)];
name.text =#"Name Not Available";
[name setBackgroundColor:[UIColor clearColor]];
[ name setFont:[UIFont fontWithName:#"Arial-BoldMT" size:30]];
name.textColor = [UIColor whiteColor];
[selectionView addSubview:name];
}
else{
UILabel *name = [[UILabel alloc]initWithFrame:CGRectMake(130, 10, 310, 55)];
name.text =[[mainArray valueForKey:#"name"] objectAtIndex:[indexPath row]];
[name setBackgroundColor:[UIColor clearColor]];
[ name setFont:[UIFont fontWithName:#"Arial-BoldMT" size:30]];
name.textColor = [UIColor whiteColor];
[selectionView addSubview:name];
}
if ([[[mainArray valueForKey:#"phone"] objectAtIndex:[indexPath row]] isEqualToString:#"Add Number"]) {
UILabel *phone = [[UILabel alloc]initWithFrame:CGRectMake(130, 70, 300, 50)];
phone.text =#"Not Available";
[phone setBackgroundColor:[UIColor clearColor]];
[ phone setFont:[UIFont fontWithName:#"Arial-BoldMT" size:25]];
phone.textColor = [UIColor whiteColor];
[selectionView addSubview:phone];
}
else{
UILabel *phone = [[UILabel alloc]initWithFrame:CGRectMake(130, 70, 300, 50)];
phone.text =[[mainArray valueForKey:#"phone"] objectAtIndex:[indexPath row]];
[phone setBackgroundColor:[UIColor clearColor]];
[ phone setFont:[UIFont fontWithName:#"Arial-BoldMT" size:25]];
phone.textColor = [UIColor whiteColor];
[selectionView addSubview:phone];
}
if ([[[mainArray valueForKey:#"email"] objectAtIndex:[indexPath row]] isEqualToString:#"Add Email"]) {
UILabel *email = [[UILabel alloc]initWithFrame:CGRectMake(420, 40, 350, 50)];
email.text =#"Email Id Not Available";
[email setBackgroundColor:[UIColor clearColor]];
[ email setFont:[UIFont fontWithName:#"Arial-BoldMT" size:20]];
email.textColor = [UIColor whiteColor];
[selectionView addSubview:email];
}
else{
UILabel *email = [[UILabel alloc]initWithFrame:CGRectMake(420, 40, 350, 50)];
email.text =[[mainArray valueForKey:#"email"] objectAtIndex:[indexPath row]];
[email setBackgroundColor:[UIColor clearColor]];
[ email setFont:[UIFont fontWithName:#"Arial-BoldMT" size:20]];
email.textColor = [UIColor whiteColor];
[selectionView addSubview:email];
}
[[cell contentView] addSubview:selectionView];
return cell;
}
what problem i face is it reach top of the table when i click any index and not right index
To use the index your table should really be broken into sections. It looks like currently you are asking the framework to scroll to a specified row and then to scroll to the top of section 0 immediately afterwards.
It may work if you use performSelector to request the scroll after a short delay (it may look nasty). Or possibly if you return -1 from the method (documentation does not support this guess).
The answer really is to use sections in your table and let the framework work as designed.
when we have section 0 then we can do like this
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
NSArray *toBeReturned = [NSArray arrayWithArray:
[#"A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z"
componentsSeparatedByString:#"|"]];
return toBeReturned;
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
int foundIndex = 0;
for (int i = 0; i< [mainArray count]; i++) {
NSString *letterString = [[[mainArray valueForKey:#"name"] objectAtIndex:i] substringToIndex:1];
NSLog(#"letterString%#",letterString);
NSLog(#"title%#",title);
if ([letterString caseInsensitiveCompare:title] == NSOrderedSame)
{
break;
}
else{
foundIndex++;
NSLog(#"founded index %d",foundIndex);
}
}
NSLog(#"founded index %d",mainArray.count);
NSLog(#"founded index %d",foundIndex);
if(foundIndex >= mainArray.count){
foundIndex = mainArray.count-1;
}
NSLog(#"founded index %d",foundIndex);
[table scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:foundIndex inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
return 1;
}
.h
#import <TapkuLibrary/TapkuLibrary.h>
#import <UIKit/UIKit.h>
#import <EventKit/EventKit.h>
#interface CalendarMonthViewController : TKCalendarMonthTableViewController{
NSMutableArray *events;
EKEventStore *eventStore;
NSDate *startDatee;
NSDate *lastDatee;
}
#property (strong,nonatomic) NSMutableArray *dataArray;
#property (strong,nonatomic) NSMutableDictionary *dataDictionary;
- (void) generateRandomDataForStartDate:(NSDate*)start endDate:(NSDate*)end;
#end
.m
#import "CalendarMonthViewController.h"
#import "AppDelegate.h"
#implementation CalendarMonthViewController
#pragma mark - View Lifecycle
- (void) viewDidLoad{
[super viewDidLoad];
[self.monthView selectDate:[NSDate month]];
}
-(void)viewWillAppear:(BOOL)animated{
[self updateTableOffset:YES];
NSLog(#"hi ha ");
}
-(void)fatchAllEvent{
eventStore = [[EKEventStore alloc] init];
if ([eventStore respondsToSelector:#selector(requestAccessToEntityType:completion:)])
{
__block typeof (self) weakSelf = self; // replace __block with __weak if you are using ARC
dispatch_async(dispatch_get_main_queue(), ^{
[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error)
{
if (granted)
{
NSLog(#" granted");
[weakSelf performSelectorOnMainThread:#selector(allCalendarEvent) withObject:nil waitUntilDone:YES];
}
else
{
NSLog(#"Not granted");
}
}];
});
}
else
{
[self allCalendarEvent];
}
}
-(void)allCalendarEvent{
NSDate *startDate = [NSDate distantPast];
NSDate *endDate = [NSDate distantFuture];
// use Dictionary for remove duplicates produced by events covered more one year segment
NSMutableDictionary *eventsDict = [NSMutableDictionary dictionaryWithCapacity:1024];
NSDate* currentStart = [NSDate dateWithTimeInterval:0 sinceDate:startDate];
int seconds_in_year = 60*60*24*365;
// enumerate events by one year segment because iOS do not support predicate longer than 4 year !
while ([currentStart compare:endDate] == NSOrderedAscending) {
NSDate* currentFinish = [NSDate dateWithTimeInterval:seconds_in_year sinceDate:currentStart];
if ([currentFinish compare:endDate] == NSOrderedDescending) {
currentFinish = [NSDate dateWithTimeInterval:0 sinceDate:endDate];
}
NSPredicate *predicate = [eventStore predicateForEventsWithStartDate:currentStart endDate:currentFinish calendars:nil];
[eventStore enumerateEventsMatchingPredicate:predicate
usingBlock:^(EKEvent *event, BOOL *stop) {
if (event) {
[eventsDict setObject:event forKey:event.eventIdentifier];
}
}];
currentStart = [NSDate dateWithTimeInterval:(seconds_in_year + 1) sinceDate:currentStart];
}
events = [[NSMutableArray alloc]init];
for (id key in eventsDict) {
id anObject = [eventsDict objectForKey:key];
[events addObject:anObject];
/* Do something with anObject. */
}
NSLog(#"all event %#",events);
CFRunLoopStop(CFRunLoopGetCurrent());
// NSLog(#"all event crash%#",events);
}
#pragma mark - MonthView Delegate & DataSource
- (NSArray*) calendarMonthView:(TKCalendarMonthView*)monthView marksFromDate:(NSDate*)startDate toDate:(NSDate*)lastDate{
if (!events) {
[self fatchAllEvent];
CFRunLoopRun();
}
NSLog(#"all event %#",events);
[self generateRandomDataForStartDate:startDate endDate:lastDate];
// NSLog(#"%#",self.dataDictionary);
NSLog(#"%#",self.dataArray);
NSLog(#"%#",self.dataDictionary);
NSLog(#"%#",[self.dataDictionary allKeys]);
return self.dataArray;
}
- (void) calendarMonthView:(TKCalendarMonthView*)monthView didSelectDate:(NSDate*)date{
// CHANGE THE DATE TO YOUR TIMEZONE
TKDateInformation info = [date dateInformationWithTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDate *myTimeZoneDay = [NSDate dateFromDateInformation:info timeZone:[NSTimeZone systemTimeZone]];
NSLog(#"Date Selected: %#",myTimeZoneDay);
[self.tableView reloadData];
}
- (void) calendarMonthView:(TKCalendarMonthView*)mv monthDidChange:(NSDate*)d animated:(BOOL)animated{
[super calendarMonthView:mv monthDidChange:d animated:animated];
[self.tableView reloadData];
}
#pragma mark - UITableView Delegate & DataSource
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
if ([[UIDevice currentDevice] userInterfaceIdiom]==UIUserInterfaceIdiomPad)
{
NSArray *views =[[NSBundle mainBundle] loadNibNamed:#"CalendarTableHeader" owner:nil options:nil];
UIView *headerView=[views objectAtIndex:0];
return headerView;
}
else
{
return nil;
}
}
- (CGFloat) tableView:(UITableView *) tableView heightForHeaderInSection:(NSInteger) section {
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
return 25;
} else {
return 0;
}
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSArray *ar = [self.dataDictionary objectForKey:[self.monthView dateSelected]];
if(ar == nil) return 0;
return [ar count];
}
- (UITableViewCell *) tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
NSArray *ar = [self.dataDictionary objectForKey:[self.monthView dateSelected]];
cell.textLabel.text = [ar objectAtIndex:indexPath.row];
return cell;
}
- (BOOL)isDate:(NSDate *)date inRangeFirstDate:(NSDate *)firstDate lastDate:(NSDate *)lastDate {
return [date compare:firstDate] == NSOrderedDescending &&
[date compare:lastDate] == NSOrderedAscending;
}
- (void) generateRandomDataForStartDate:(NSDate*)start endDate:(NSDate*)end{
// this function sets up dataArray & dataDictionary
// dataArray: has boolean markers for each day to pass to the calendar view (via the delegate function)
// dataDictionary: has items that are associated with date keys (for tableview)
NSMutableArray *arrayOfDates = [[NSMutableArray alloc ]init];
NSMutableArray *arrayOfNames = [[NSMutableArray alloc ]init];
// NSLog(#"Delegate Range: %# %# %d",start,end,[start daysBetweenDate:end]);
NSDateFormatter *newformater=[[[NSDateFormatter alloc]init]autorelease];
[newformater setDateFormat:#"yyyy-MM-dd HH:mm:ss "];
NSDate *startD = [newformater dateFromString:[newformater stringFromDate:start]];
NSDate *endD = [newformater dateFromString:[newformater stringFromDate:end]];
NSLog(#"%#",events);
BOOL isAttempt = NO;
for (int i =0; i<arrayOfDates.count; i++) {
if ([start isEqualToDate:[arrayOfDates objectAtIndex:i]]) {
[self.dataDictionary setObject:[NSArray arrayWithObjects:[arrayOfNames objectAtIndex:i],nil] forKey:start];
[self.dataArray addObject:[NSNumber numberWithBool:YES]];
isAttempt = YES;
}
else{
isAttempt = NO;
}
}
if (!isAttempt) {
[self.dataArray addObject:[NSNumber numberWithBool:NO]];
}
for (int i = 0; i<events.count; i++) {
NSDate *eventDate = [[events valueForKey:#"startDate"] objectAtIndex:i];
NSString *eventName = [[events valueForKey:#"title"]objectAtIndex:i];
NSLog(#"startreal%#",start);
NSLog(#"endreal%#",end);
NSLog(#"eventName:::%#",eventName);
NSLog(#"start%#",startD);
NSLog(#"end%#",endD);
NSLog(#"eventDate%#",eventDate);
if([self isDate:eventDate inRangeFirstDate:startD lastDate:endD]){
[arrayOfDates addObject:eventDate];
[arrayOfNames addObject:eventName];
}else{
}
}
NSLog(#"eventdate = %#",arrayOfDates);
NSLog(#"eventName = %#",arrayOfNames);
// the dates that we have will go thorought for loop and we wil check if its between start and end date then we will add that object to datadictionary or wont
[self.dataArray removeAllObjects];
[self.dataDictionary removeAllObjects];
self.dataArray = [NSMutableArray array];
self.dataDictionary = [NSMutableDictionary dictionary];
NSDate *d = start;
while(YES){
BOOL isAttempt = NO;
for (int i =0; i<arrayOfDates.count; i++) {
if ([d isEqualToDate:[arrayOfDates objectAtIndex:i]]) {
[self.dataDictionary setObject:[NSArray arrayWithObjects:[arrayOfNames objectAtIndex:i],nil] forKey:d];
[self.dataArray addObject:[NSNumber numberWithBool:YES]];
isAttempt = YES;
}
else{
isAttempt = NO;
}
}
if (!isAttempt) {
[self.dataArray addObject:[NSNumber numberWithBool:NO]];
}
TKDateInformation info = [d dateInformationWithTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
info.day++;
d = [NSDate dateFromDateInformation:info timeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
if([d compare:end]==NSOrderedDescending) break;
}
}
-(void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
[self updateTableOffset:YES];
}
- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return YES;
}
#end

NSArray Values are Display after touche in screen in Tableview

- (void)viewDidLoad {
detailView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 330, 380) style:UITableViewStylePlain];
detailView.rowHeight = 55.0f;
detailView.dataSource =self;
detailView.delegate =self;
NSLog(#"finish0");
[self.view addSubview:detailView];
self.title = NSLocalizedString(#"Routes", nil);
self.detailArray = [[NSMutableArray alloc] init];
url = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=%#&destination=%f,%f&sensor=false",start1,center.latitude,center.longitude];
NSURL *googleRequestURL=[NSURL URLWithString:url];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
NSError* error;
NSMutableDictionary* parsedJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *allkeys = [parsedJson allKeys];
for(int i = 0; i < allkeys.count; i++){
if([[allkeys objectAtIndex:i] isEqualToString:#"routes"]){
NSArray *arr = [parsedJson objectForKey:#"routes"];
NSDictionary *dic = [arr objectAtIndex:0];
legs = [dic objectForKey:#"legs"];
for(int i = 0; i < legs.count; i++){
NSArray *stepsArr = [[legs objectAtIndex:i] objectForKey:#"steps"];
for (int i = 0; i < stepsArr.count; i++) {
[self.detailArray addObject:[[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"] ];
string = [self.detailArray componentsJoinedByString:#","];
NSLog(#"string%#",string);
[self stringByStrippingHTML];
self.detail=[string componentsSeparatedByString:#","];
[self.detail retain];
[detailView reloadData];
}}}}
});
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section{
return [detail count];
NSLog(#"table2");
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"table4");
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(5.0f, 0.0f, 300.0f, 60.0f)];
label.text=[NSString stringWithFormat:#"%#",[detail objectAtIndex:indexPath.row]];
label.numberOfLines = 3;
label.font = [UIFont fontWithName:#"Helvetica" size:(12.0)];
label.lineBreakMode = UILineBreakModeWordWrap;
label.textAlignment = UITextAlignmentLeft;
[cell.contentView addSubview:label];
[label release];
return cell;
}
-(NSString *) stringByStrippingHTML {
NSRange r;
while ((r = [string rangeOfString:#"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
string = [string stringByReplacingCharactersInRange:r withString:#""];
return string;
}
In The coding the values of self.detail(array) display after touches the screen in TableView.i need to display the values immediately when i enter the TableView. please any one help if you know. and tell me why the values of NSArray display only after touch or scroll the tableview.
try this
[self.detailView performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:NO];
instead of [detailView reloadData];
You need to reload the table view after you have finished downloading the data and populating your array with the result. That is
url = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=%#&destination=%f,%f&sensor=false",start1,center.latitude,center.longitude];
NSURL *googleRequestURL=[NSURL URLWithString:url];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
NSError* error;
NSMutableDictionary* parsedJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *allkeys = [parsedJson allKeys];
for(int i = 0; i < allkeys.count; i++){
if([[allkeys objectAtIndex:i] isEqualToString:#"routes"]){
NSArray *arr = [parsedJson objectForKey:#"routes"];
NSDictionary *dic = [arr objectAtIndex:0];
legs = [dic objectForKey:#"legs"];
for(int i = 0; i < legs.count; i++){
NSArray *stepsArr = [[legs objectAtIndex:i] objectForKey:#"steps"];
for (int i = 0; i < stepsArr.count; i++) {
[self.detailArray addObject:[[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"] ];
string = [self.detailArray componentsJoinedByString:#","];
NSLog(#"string%#",string);
[self stringByStrippingHTML];
self.detail=[string componentsSeparatedByString:#","];
[self.detail retain];
}}}}
[detailView reloadData];
}
Also to explain why the table loads after you scroll the TableView; When you scroll in the table view the delegate method -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath (among with others) will be called to update the tableview.

NSMutableArray Display Null Value in Table View

- (void)viewDidLoad {
self.detailView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 480) style:UITableViewStylePlain];
self.detailView.dataSource = self;
self.detailView.delegate = self;
self.detailView.multipleTouchEnabled=YES;
[self.view addSubview:self.detailView];
[super viewDidLoad];
self.title = NSLocalizedString(#"Routes", nil);
self.detailArray = [[NSMutableArray alloc] init];
NSString *url = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=Chennai&destination=Madurai&sensor=false"];
NSURL *googleRequestURL=[NSURL URLWithString:url];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
NSString *someString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSError* error;
NSMutableDictionary* parsedJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *allkeys = [parsedJson allKeys];
for(int i = 0; i < allkeys.count; i++){
if([[allkeys objectAtIndex:i] isEqualToString:#"routes"]){
NSArray *arr = [parsedJson objectForKey:#"routes"];
NSDictionary *dic = [arr objectAtIndex:0];
NSArray *legs = [dic objectForKey:#"legs"];
for(int i = 0; i < legs.count; i++){
NSArray *stepsArr = [[legs objectAtIndex:i] objectForKey:#"steps"];
for (int i = 0; i < stepsArr.count; i++) {
NSLog(#"HTML INSTRUCTION %#", [[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"]);
NSLog(#"############################");
[self.detailArray addObject:[[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"] ];
}
}
}
}
});
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section{
return [self.detailArray count];
}
-(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];
}
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, 5.0f, 300.0f, 30.0f)];
label.text=[NSString stringWithFormat:#"%#",[self.detailArray objectAtIndex:indexPath.row]];
label.numberOfLines = 3;
label.font = [UIFont fontWithName:#"Helvetica" size:(12.0)];
label.lineBreakMode = UILineBreakModeWordWrap;
label.textAlignment = UITextAlignmentLeft;
[cell.contentView addSubview:label];
[label release];
return cell;
}
i want to display the detailArray in the Table View.But it display null values in Table View.But in NSlog it display current values.The detailArray having set of direction values. is any possible to display in TableView.if i give constant value in displayArray its show correctly in TableView. please help me if Any one know.i am waiting for your valuable Answers,Thanks.
UPDATED
After add whole data (values) in after retain it and reload TableView like bellow...
[self.detailArray retain];
[self.detailView reloadData];
i am sure your problem solved... :)
Remove [self.detailView reloadData]; from cellForRowAtIndexPath method. and also remove tableView.delegate = self; in same method.
and remember [super viewDidLoad]; must write at top of viewDidLoad.
Edit
just change your four array as below.
NSArray *legs=(NSArray *)[dic objectForKey:#"legs"];
NSArray *arr = (NSArray *)[parsedJson objectForKey:#"routes"];
NSArray *legs = (NSArray *)[dic objectForKey:#"legs"];
NSArray *stepsArr = (NSArray *)[[legs objectAtIndex:i] objectForKey:#"steps"];
Why are you setting detailView delegate and datasource 2 times in viewDidLoad. Please format the code first then it will be easy for us to describe the problem.
self.detailView.dataSource=self;
self.detailView.delegate=self;
self.detailView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 480) style:UITableViewStylePlain];
self.detailView.dataSource = self;
self.detailView.delegate = self;

how to assign a static row at the first and last row of dynamically allocated data in table view

i m parsing a json file and populating it in my table view what i want to assign is a static row.at the first and last row of my tableview named as Var tycker du. but doing so.it overlaps the dynamically allocated data from json file..could you guys help me out below is the code.
static NSString * const kCellTextKey = #"CellTextKey";
static NSString * const kCellStateKey = #"CellStateKey";
static NSString* kAppId = #"126013844184727";
#define KFBAccessToken #"126013844184727"
#define KFBExpirationDate #"KFBExpirationDate"
#implementation Tab5
#synthesize tableview1,jsonData,jsonArray,story,media1,url,descriptiondesc,media2;
#synthesize arForIPs = _arForIPs;
- (void)viewDidLoad {
[super viewDidLoad];
objMan = [[HJObjManager alloc] initWithLoadingBufferSize:6 memCacheSize:20];
self.arForIPs=[NSMutableArray array];
self.tableview1.backgroundColor=[UIColor clearColor];
[self.tableview1 setAllowsSelectionDuringEditing:TRUE];
jsonurl=[NSURL URLWithString:#"http://dev-parkguiden.knutpunkten.se/Api/GetPark? parkid=3"];
NSURLRequest *request = [NSURLRequest requestWithURL:jsonurl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
connection1=[[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
self.jsonData=[NSData dataWithContentsOfURL:jsonurl];
NSDictionary *items=[NSJSONSerialization JSONObjectWithData:self.jsonData options:NSJSONReadingMutableLeaves error:nil];
items1 = [items objectForKey:#"ThingsTodo"];
story = [[NSMutableArray array]retain];
media1 = [[NSMutableArray array]retain];
url=[[NSMutableArray array]retain];
media2=[[NSMutableArray array]retain];
descriptiondesc=[[NSMutableArray array]retain];
dog=[[NSMutableArray array]retain];
arr=[[NSMutableArray array]retain];
bose=[[NSMutableArray array]retain];
for (NSDictionary *item in items1)
{
[self.story addObject:[item objectForKey:#"Name"]];
[self.media1 addObject:[item objectForKey:#"Status"]];
//[self.media2 addObject:[item objectForKey:#"Image"]];
}
//NSLog(#"room:%#",items1);
[self makeNewArray];
}
-(void)makeNewArray
{
for ( int i=0; i<[self.media1 count]; i++)
{
NSDictionary *boy=[self.media1 objectAtIndex:i];
NSString *str=[[NSString alloc]initWithFormat:#"%#",boy];
//NSLog(#"the value:%#",str);
if([str isEqualToString:#"1"])
{
text = [self.story objectAtIndex:i];
NSString *text1 = [NSString stringWithFormat:#"%#",text];
NSNumber *state = [NSNumber numberWithBool:NO];
dict=[NSDictionary dictionaryWithObjectsAndKeys:text1,kCellTextKey,state,kCellStateKey,nil];
[arr addObject:dict];
// [dog addObject:[self.story objectAtIndex:i]];
}
dog=[arr mutableCopy];
NSLog(#"wat hav i got:%#",arr);
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [dog count];
}
- (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]; }
// cell.textLabel.text=[dog objectAtIndex:indexPath.row];
NSDictionary *rowData = [dog objectAtIndex:indexPath.row];
cell.textLabel.text = [rowData objectForKey:kCellTextKey];
if ([[rowData objectForKey:kCellStateKey] boolValue]) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
} else {
cell.accessoryType = UITableViewCellAccessoryNone;
[bose removeObject:[newDict valueForKey:#"CellTextKey"]];
// NSLog(#"object going to get removed:%#",bose);
}
sectionRows = [tableview1 numberOfRowsInSection:[indexPath section]];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *dict = [dog objectAtIndex:indexPath.row];
BOOL newState = ![[dict objectForKey:kCellStateKey] boolValue];
newDict = [NSDictionary dictionaryWithObjectsAndKeys:[dict objectForKey:kCellTextKey], kCellTextKey, [NSNumber numberWithBool:newState], kCellStateKey, nil];
[dog replaceObjectAtIndex:indexPath.row withObject:newDict];
[bose addObject:[newDict valueForKey:#"CellTextKey"]];
NSLog(#"the current added data:%#",bose);
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
}
}
hey try out with this solution
-(void)makeNewArray
{
for ( int i=0; i<[self.media1 count]; i++)
{
NSDictionary *boy=[self.media1 objectAtIndex:i];
NSString *str=[[NSString alloc]initWithFormat:#"%#",boy];
//NSLog(#"the value:%#",str);
if([str isEqualToString:#"1"])
{
text = [self.story objectAtIndex:i];
NSString *text1 = [NSString stringWithFormat:#"%#",text];
NSNumber *state = [NSNumber numberWithBool:NO];
dict=[NSDictionary dictionaryWithObjectsAndKeys:text1,kCellTextKey,state,kCellStateKey,nil];
[arr addObject:dict];
// [dog addObject:[self.story objectAtIndex:i]];
}
}
NSDictionary *dict;
dict = [NSDictionary dictionaryWithObjectsAndKeys:
#"Var tycker du", #"CellTextKey",
#"0", #"CellStateKey", nil];
[dog addObject:dict];
for(int i=0; i<arr.count; i++){
[dog addObject:[arr objectAtIndex:i]];
}
[dog addObject:dict];
// dog=[arr mutableCopy];
NSLog(#"wat hav i got:%#",dog);
}

Obj-C, iOS, How do I sort by value and not key, sortedArrayUsingSelector, currently #selector(compare:)]

I need to sort by value instead of Key, I think....
Heres where I populate my arrarys
const char *sql = "select cid, category from Categories ORDER BY category DESC";
sqlite3_stmt *statementTMP;
int error_code = sqlite3_prepare_v2(database, sql, -1, &statementTMP, NULL);
if(error_code == SQLITE_OK) {
while(sqlite3_step(statementTMP) == SQLITE_ROW)
{
int cid = sqlite3_column_int(statementTMP, 0);
NSString *category = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statementTMP, 1)];
NSArray *arr=[[NSArray alloc]initWithObjects:category,nil];
[arrayTmp setObject:arr forKey:[NSString stringWithFormat:#"%i",cid]];
[self.cidList addObject:[NSString stringWithFormat:#"%i",cid]];
[category release];
[arr release];
}
}
sqlite3_finalize(statementTMP);
sqlite3_close(database);
self.allCategories = arrayTmp;
[arrayTmp release];
Heres the method where the arrays are re-sorted.
- (void)resetSearch {
NSMutableDictionary *allCategoriesCopy = [self.allCategories mutableDeepCopy];
self.Categories = allCategoriesCopy;
[allCategoriesCopy release];
NSMutableArray *keyArray = [[NSMutableArray alloc] init];
[keyArray addObject:UITableViewIndexSearch];
[keyArray addObjectsFromArray:[[self.allCategories allKeys]
sortedArrayUsingSelector:#selector(compare:)]];
self.keys = keyArray;
[keyArray release];
}
This is a problem i've had for some time, last time I looked at this I could find an altervative to sortedArrayUsingSelector compare?
EDIT
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger section = [indexPath section];
NSUInteger row = [indexPath row];
NSString *key = [keys objectAtIndex:section];
NSArray *nameSection = [Categories objectForKey:key];
static NSString *SectionsTableIdentifier = #"SectionsTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
SectionsTableIdentifier ];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier: SectionsTableIdentifier ] autorelease];
}
cell.textLabel.text = [nameSection objectAtIndex:row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger section = [indexPath section];
NSUInteger row = [indexPath row];
NSString *key = [keys objectAtIndex:section];
NSArray *nameSection = [Categories objectForKey:key];
NSLog(#"the selected cid is = %i",[key intValue]);
selectButton.enabled = YES;
}
Anyone?
Your obviously attempting to construct an array for use in the -[UITableviewDatasource sectionIndexTitlesForTableView:]. As such, you need an array that looks like this (pseudo-code):
[UITableViewIndexSearch, 0_sectionTitle, 1_sectionTitle, 2_sectionTitle, ...]
I think your immediate problem is that you try to add the UITableViewIndexSearch string constant to the array before you sort which makes it impossible for it end up as the first element unless all your other elements sort below U.
The fix is simple, just add the constant after the sort. You can clean the code up while you're at it:
NSMutableArray *secIdx=[NSMutableArray arrayWithCapacity:[[self.allCategories allKeys] count]];
[secIdx addObjectsFromArray:[self.allCategories allKeys]];
[secIdx sortUsingSelector:#selector(compare:)];
[secIdx insertObject:UITableViewIndexSearch atIndex:0];
self.keys=secIdx;
Note that secIdx is autoreleased so you don't have to release it.
Aside from this problem, your code has a lot of unnecessary/dangerous elements that will make your app fragile and hard to maintain.
You are using a lot of init for objects that you could use autoreleased convenience methods for. The 'init`s poise the risk of memory leaks but give you no advantage.
You need to wrap scalar values in objects so they can be easily managed in collections.
You are using an unnecessary array.
You can rewrite the first block like so:
const char *sql = "select cid, category from Categories ORDER BY category DESC";
sqlite3_stmt *statementTMP;
int error_code = sqlite3_prepare_v2(database, sql, -1, &statementTMP, NULL);
if(error_code == SQLITE_OK) {
NSNumber *cidNum; //... move variable declerations outside of loop
NSString *category; //.. so they are not continously recreated
[self.allCategories removeAllObjects]; //... clears the mutable dictionary instead of replacing it
while(sqlite3_step(statementTMP) == SQLITE_ROW){
cidNum=[NSNumber numberWithInt:(sqlite3_column_int(statementTMP, 0))];
category=[NSString stringWithUTF8String:(char *)sqlite3_column_text(statementTMP, 1)];
//... adding the autoreleased category and cidNum to array/dictionary automatically retains them
[self.allCategories addObject:category forKey:cidNum];
[self.cidList addObject:cidNum];
//[category release]; ... no longer needed
//[arr release]; ... no longer needed
}
}
sqlite3_finalize(statementTMP);
sqlite3_close(database);
//self.allCategories = arrayTmp; ... no longer needed
//[arrayTmp release]; ... no longer needed
Use -sortedArrayUsingComparator: (or -sortedArrayUsingFunction:context: if you can't use blocks). Example:
NSDictionary *categories = [self allCategories];
NSArray *keysSortedByValue = [[categories allKeys] sortedArrayUsingComparator:
^(id left, id right) {
id lval = [categories objectForKey:left];
id rval = [categories objectForKey:right];
return [lval compare:rval];
}];
You could make a small model class Category and implement compare inside of it, then sort an array of those objects using that compare:.
Here's some info - How to sort an NSMutableArray with custom objects in it?
Perhaps you're looking for NSSortDescriptor (and the corresponding sort method, -[NSArray sortedArrayUsingDescriptors]) and friends?
If I understood correctly then what you wish to do to get categories from database & display it on a tableView with alphabetical sorting, index on right & search bar on top. Ideally, you would like to display the Contacts application kind of a view. If that's correct, use below code for fetching items from DB & rebuilding (or resetting) it -
const char *sql = "select cid, category from Categories ORDER BY category DESC";
sqlite3_stmt *statementTMP;
NSMutableArray *arrayTmp = [[NSMutableArray alloc] init];
int error_code = sqlite3_prepare_v2(database, sql, -1, &statementTMP, NULL);
if(error_code == SQLITE_OK) {
while(sqlite3_step(statementTMP) == SQLITE_ROW) {
int cid = sqlite3_column_int(statementTMP, 0);
NSString *category = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statementTMP, 1)];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:category forKey:#"Category"];
[dict setObject:[NSNumber numberWithInt:cid] forKey:#"CID"];
[arrayTmp addObject:dict];
[dict release];
[category release];
}
}
sqlite3_finalize(statementTMP);
sqlite3_close(database);
self.allCategories = arrayTmp;
[arrayTmp release];
And then rebuild the items using this function -
- (void)rebuildItems {
NSMutableDictionary *map = [NSMutableDictionary dictionary];
for (int i = 0; i < allCategories.count; i++) {
NSString *name = [[allCategories objectAtIndex:i] objectForKey:#"Category"];
NSString *letter = [name substringToIndex:1];
letter = [letter uppercaseString];
if (isdigit([letter characterAtIndex:0]))
letter = #"#";
NSMutableArray *section = [map objectForKey:letter];
if (!section) {
section = [NSMutableArray array];
[map setObject:section forKey:letter];
}
[section addObject:[allCategories objectAtIndex:i]];
}
[_items release];
_items = [[NSMutableArray alloc] init];
[_sections release];
_sections = [[NSMutableArray alloc] init];
NSArray* letters = [map.allKeys sortedArrayUsingSelector:#selector(caseInsensitiveCompare:)];
for (NSString* letter in letters) {
NSArray* items = [map objectForKey:letter];
[_sections addObject:letter];
[_items addObject:items];
}
}
Now, displaying items in tableView, use below methods -
#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)aTableView {
if (_sections.count)
return _sections.count;
else
return 1;
}
- (NSInteger)tableView:(UITableView*)tableView sectionForSectionIndexTitle:(NSString *)title
atIndex:(NSInteger)index {
if (tableView.tableHeaderView) {
if (index == 0) {
[tableView scrollRectToVisible:tableView.tableHeaderView.bounds animated:NO];
return -1;
}
}
NSString* letter = [title substringToIndex:1];
NSInteger sectionCount = [tableView numberOfSections];
for (NSInteger i = 0; i < sectionCount; i++) {
NSString* section = [tableView.dataSource tableView:tableView titleForHeaderInSection:i];
if ([section hasPrefix:letter]) {
return i;
}
}
if (index >= sectionCount) {
return sectionCount-1;
} else {
return index;
}
}
- (NSArray*)lettersForSectionsWithSearch:(BOOL)withSearch withCount:(BOOL)withCount {
if (isSearching)
return nil;
if (_sections.count) {
NSMutableArray* titles = [NSMutableArray array];
if (withSearch) {
[titles addObject:UITableViewIndexSearch];
}
for (NSString* label in _sections) {
if (label.length) {
NSString* letter = [label substringToIndex:1];
[titles addObject:letter];
}
}
if (withCount) {
[titles addObject:#"#"];
}
return titles;
} else {
return nil;
}
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
return [self lettersForSectionsWithSearch:YES withCount:NO];
}
- (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section {
if (_sections.count) {
NSArray* items = [_items objectAtIndex:section];
return items.count;
} else {
return _items.count;
}
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if (_sections.count)
return [_sections objectAtIndex:section];
return nil;
}
- (id)tableView:(UITableView *)tableView objectForRowAtIndexPath:(NSIndexPath *)indexPath {
if (_sections.count) {
NSArray *section = [_items objectAtIndex:indexPath.section];
return [section objectAtIndex:indexPath.row];
} else {
return [_items objectAtIndex:indexPath.row];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// Create your UITableViewCell.
// Configure the cell.
NSDictionary *dict = [self tableView:tableView objectForRowAtIndexPath:indexPath];
cell.textLabel.text = [dict objectForKey:#"Category"];
cell.detailTextLabel.text = [NSString stringWithFormat:%d, [[dict objectForKey:#"CID"] intValue]];
return cell;
}
#pragma mark -
#pragma mark Table view delegate
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
if (isSearching)
return nil;
NSString *title = #"";
if (_sections.count) {
title = [[_sections objectAtIndex:section] substringToIndex:1];
} else {
return nil;
}
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 20)];
view.backgroundColor = [UIColor colorWithRed:(58/255.0) green:(27/255.0) blue:(6/255.0) alpha:1.0];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 1, 50, 18)];
label.textColor = [UIColor whiteColor];
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont boldSystemFontOfSize:17.0];
label.text = title;
[view addSubview:label];
[label release];
return [view autorelease];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *dict = [self tableView:tableView objectForRowAtIndexPath:indexPath];
NSLog(#"selected row id:%d, name:%#", [dict objectForKey:#"Category"], [[dict objectForKey:#"CID"] intValue]);
}
The rest part is implementing the UISearchBarDelegate and implementing searching of tableView which can be done using below code:
- (void)searchBar:(UISearchBar *)searchbar textDidChange:(NSString *)searchText {
[_sections removeAllObjects];
[_items removeAllObjects];
if([searchText isEqualToString:#""] || searchText == nil) {
[self rebuildItems];
return;
}
NSInteger counter = 0;
for(NSDictionary *dict in allCategories) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSRange r = [[dict objectForKey:#"Category"] rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(r.location != NSNotFound) {
if(r.location == 0) {
[_items addObject:dict];
}
}
counter++;
[pool release];
}
[contactList reloadData];
}
Hope this is what you're looking for.
On your sorting function u should try this:
NSArray *cntxt; //im not sure this is the correct type that ur using on keyArray
[keyArray addObjectsFromArray:[self.allCategories allKeys]];
[keyArray sortUsingFunction:compareFunction context:cntxt];
And the compare function you modify to your needs
NSInteger compareFunction(id x, id y, void *context) {
//NSArray *ctxt = context;
NSArray *c1 = x;
NSArray *c2 = y;
if ([c1 value] < [c2 value])
return NSOrderedDescending;
else if ([c1 value] > [c2 value])
return NSOrderedAscending;
else
return NSOrderedSame;
}
Edit: After reading your comments and after relooking at your code, it seems like that your keyArray as objects of the type NSString, so you should change:
NSInteger compareFunction(id x, id y, void *context) {
//NSString *ctxt = context;
NSString *c1 = x;
NSString *c2 = y;
NSComparisonResult result;
result = [c1 compare:c2];
if (result<0)
return NSOrderedAscending;
else if (result>0)
return NSOrderedDescending;
else
return NSOrderedSame;
}