Replacing Not adding: UICollectionView - iphone

I am creating a client app for Instagram the gets pictures, however when the user gets to the bottom of the page it is is supposed to bring a new group of uicollectionviewcell's however it replaces the existing ones and i cannot see them anymore unless i refresh. All the nessecary code is provided below, thanks for your help in advance:
#interface StreamViewController () <UITextFieldDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
#property (nonatomic, strong) NSMutableDictionary *timelineResponse;
#property (nonatomic, strong) CredentialStore *credentialStore;
#property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
#end
#implementation StreamViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self refreshInstagram];
//Refresh
UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
[refreshControl addTarget:self action:#selector(startRefresh:)
forControlEvents:UIControlEventValueChanged];
[self.collectionView addSubview:refreshControl];
//Instigate Navigation Bar Buttons
UIButton *barButton = [UIButton buttonWithType:UIButtonTypeCustom];
[barButton setTitle:#"" forState:UIControlStateNormal];
[barButton setBackgroundImage:[UIImage imageNamed:#"barButton.png"] forState:UIControlStateNormal];
[barButton setBackgroundImage:[UIImage imageNamed:#"barButton_s.png"] forState:UIControlStateHighlighted];
[barButton addTarget:self action:#selector(didTapBarButton:) forControlEvents:UIControlEventTouchUpInside];
barButton.frame = CGRectMake(0.0f, 0.0f, 30.0f, 30.0f);
UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:barButton];
self.navBar.leftBarButtonItem = barButtonItem;
UIButton *postButton = [UIButton buttonWithType:UIButtonTypeCustom];
[postButton setTitle:#"" forState:UIControlStateNormal];
[postButton setBackgroundImage:[UIImage imageNamed:#"pen_usIMG.png"] forState:UIControlStateNormal];
[postButton setBackgroundImage:[UIImage imageNamed:#"pen_sIMG.png"] forState:UIControlStateHighlighted];
[postButton addTarget:self action:#selector(didTapPostButton:) forControlEvents:UIControlEventTouchUpInside];
postButton.frame = CGRectMake(0.0f, 0.0f, 30.0f, 30.0f);
UIBarButtonItem *postButtonItem = [[UIBarButtonItem alloc] initWithCustomView:postButton];
self.navBar.rightBarButtonItem = postButtonItem;
//Reload by default
[self.collectionView reloadData];
}
//Global refresh Instagram Method
- (void)refreshInstagram {
[[InstagramClient sharedClient] getPath:#"users/self/feed"
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Response: %#", responseObject);
self.timelineResponse = [responseObject mutableCopy];
[self.collectionView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure: %#", error);
}];
}
- (void)nextInstagramPage:(NSIndexPath *)indexPath{
NSDictionary *page = self.timelineResponse[#"pagination"];
NSString *nextPage = page[#"next_url"];
[[InstagramClient sharedClient] getPath:[NSString stringWithFormat:#"%#",nextPage] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
self.timelineResponse = [responseObject mutableCopy];
[self.timelineResponse addEntriesFromDictionary:responseObject];
[self.collectionView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure: %#", error);
}];
}
- (NSMutableArray *)entries {
return self.timelineResponse[#"data"];
}
- (NSArray *)pages {
return self.timelineResponse[#"pagination"];
}
- (NSURL *)imageUrlForEntryAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *entry = [self entries][indexPath.row];
NSString *imageUrlString = entry[#"images"][#"standard_resolution"][#"url"];
return [NSURL URLWithString:imageUrlString];
}
#pragma mark - UICollectionViewDelegate
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
//int y = arc4random() % 200+50;
return CGSizeMake(150, 150);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
RNBlurModalView *modal = [[RNBlurModalView alloc] initWithViewController:self title:#"Item Tapped!" message:#"Thank God its working"];
[modal show];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
if (scrollView.contentOffset.y == roundf(scrollView.contentSize.height-scrollView.frame.size.height)) {
NSLog(#"we are at the endddd");
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self nextInstagramPage:indexPath];
}
}
#pragma mark - UICollectionViewDataSource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return [[self entries] count];
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
ImageCell *cell = (ImageCell *)[collectionView dequeueReusableCellWithReuseIdentifier:#"imageCell"
forIndexPath:indexPath];
NSURL *url = [self imageUrlForEntryAtIndexPath:indexPath];
NSLog(#"%#", url);
[cell.imageView setImageWithURL:url];
cell.backgroundColor = [UIColor whiteColor];
return cell;
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
#pragma mark - NavigationBarButtons
- (void)didTapBarButton:(id)sender {
[self.sidePanelController showLeftPanelAnimated:YES];
}
- (void)startRefresh:(UIRefreshControl *)sender {
[self refreshInstagram];
[sender endRefreshing];
}
-(void)didTapPostButton:(id)sender {
}
#end

Your problem is probably arising from this line:
self.timelineResponse = [responseObject mutableCopy];
At this point, all the objects in timelineResponse are deleted. Try removing this line and I bet you'll be fine.

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

UITableView - methods are not being called

I have a subview in which I build a UITableview, I've set the delegate and datasource to the subview but for some reason the table methods are not being called...can someone look over my code and see what I am doing wrong? Thanks
.h file
#interface TwitterController : UIView <UITableViewDelegate, UITableViewDataSource> {
UIButton* btnCloseView;
UITableView* tblTweets;
UIImageView* imgTwitterIcon;
ColorController* colorManager;
NSMutableArray* tweetsArray;
NSMutableArray* tableData;
NSString* twitterID;
}
#property (nonatomic, retain) NSString* twitterID;
- (NSMutableArray* ) getTweets;
- (void) sendNotification : (id) sender;
#end
.m file
#import "TwitterController.h"
#implementation TwitterController
#synthesize twitterID;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
colorManager = [ColorController new];
}
return self;
}
/*- (void)drawRect:(CGRect)rect {
}*/
- (void)layoutSubviews {
imgTwitterIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"imgTwitterBird"]];
CGRect twitterIconFrame = [imgTwitterIcon frame];
twitterIconFrame.origin.x = 50.0;
twitterIconFrame.origin.y = 20.0;
tblTweets = [[UITableView alloc] initWithFrame:CGRectMake(50.0, 25.0, 220.0, 500.0)];
tblTweets.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
tblTweets.separatorColor = [colorManager setColor:176.0:196.0:222.0];
tblTweets.layer.borderWidth = 1.0;
tblTweets.rowHeight = 20.0;
tblTweets.scrollEnabled = YES;
tblTweets.delegate = self;
tblTweets.dataSource = self;
tableData = [self getTweets];
UIImage* imgCloseButton = [UIImage imageNamed:#"btnCloseWindow.png"];
CGSize imageSize = imgCloseButton.size;
btnCloseView = [[UIButton alloc] initWithFrame: CGRectMake(220.0, 550.0, imageSize.width, imageSize.height)];
[btnCloseView setImage:[UIImage imageNamed:#"btnCloseWindow.png"] forState:UIControlStateNormal];
[btnCloseView addTarget:self action:#selector(sendNotification:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:tblTweets];
[self addSubview:imgTwitterIcon];
[self addSubview:btnCloseView];
}
- (NSMutableArray*) getTweets {
//array to hold tweets
tweetsArray = [[NSMutableArray alloc] init];
twitterID = #"Pruit_Igoe";
///set up a NSURL to the twitter API
NSURL* twitterAPI = [NSURL URLWithString:[NSString stringWithFormat:#"https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=%#&count=10", twitterID]];
//get last 10 tweets (max is 20)
TWRequest *twitterRequest = [[TWRequest alloc] initWithURL:twitterAPI
parameters:nil requestMethod:TWRequestMethodGET];
// Notice this is a block, it is the handler to process the response
[twitterRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if ([urlResponse statusCode] == 200) {
// The response from Twitter is in JSON format
// Move the response into a dictionary and print
NSError *error;
NSDictionary *tweetsDict = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
for(NSDictionary* thisTweetDict in tweetsDict) {
[tweetsArray addObject:[thisTweetDict objectForKey:#"text"]];
}
}
else
NSLog(#"Twitter error, HTTP response: %i", [urlResponse statusCode]);
}];
return tweetsArray;
}
#pragma mark Table Management
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [tableData count];
NSLog(#"%i", [tableData count]); //does not log!
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [tableData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"tableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.textColor = [UIColor colorWithRed:66.0/255.0 green:66.0/255.0 blue:66.0/255.0 alpha:1];
cell.textLabel.font = [UIFont fontWithName:#"Helvetica-Bold" size: 13.0];
cell.textLabel.text = [tweetsArray objectAtIndex:indexPath.row];
CGRect cellFrame = [cell frame];
cellFrame.size.height = 25.0;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSString* thisTweet = [tableData objectAtIndex:indexPath.row];
}
#pragma mark Close Window
- (void) sendNotification : (id) sender {
NSMutableDictionary* userData = [[NSMutableDictionary alloc] init];
[userData setObject:#"closeTwitter" forKey:#"theEvent"];
[[NSNotificationCenter defaultCenter] postNotificationName:#"theMessenger" object:self userInfo: userData];
}
#end
I think you are not allocate and initialize tableData. Write it tableData = [[NSMutableArray alloc] init]; in - (id)initWithFrame:(CGRect)frame method or - (void)layoutSubviews method. Just try it.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
NSLog(#"%i", [tableData count]);
return [tableData count];
//NSLog(#"%i", [tableData count]); //does not log!
}
If the output is zero, tableData array is empty. Check it tableData array
You should do all the initialization (tblTweets for example) in initWithFrame:.
layoutSubviews is ment for laying out subviews.
In fact your code will (should) work if you move all the code fromLayoutSubviews to initWithFrame:. You can then move parts of the code (the laying out part) back.
EDIT: when you move initializing code you will probably also have to add [tblTweets reloadData]; right after tableData = [self getTweets];

Crash after returning to tableview

So I am writing an app to read an rss feed, and display the contents in a tableview. It also lets the user play back mp3s that it finds for each item. Anyway the app seemed to be running fine before I started adding new views. Now every time I come back from a view and scroll around a bit, I get "Program received signal "SIGABRT"" or something similar.
here's most of the program:
- (IBAction)playAction:(id)sender
{
// Get row
UIButton *senderButton = (UIButton *)sender;
UITableViewCell *buttonCell =
(UITableViewCell *) [[senderButton superview] superview];
NSInteger buttonRow = [[self.tableView
indexPathForCell:buttonCell] row];
// Entry for row
RSSEntry *senderEntry = [_allEntries objectAtIndex:buttonRow];
// This is where _allEntries gets filled
- (void)requestFinished:(ASIHTTPRequest *)request {
[_queue addOperationWithBlock:^{
NSError *error;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[request responseData]
options:0 error:&error];
if (doc == nil)
{
NSLog(#"Failed to parse %#", request.url);
}
else
{
NSMutableArray *entries = [NSMutableArray array];
[self parseRss:doc.rootElement entries:entries];
if ([_allEntries count] > 0) {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
// Update
int i=0;
while (![[[_allEntries objectAtIndex:i] articleUrl] isEqualToString:[[entries objectAtIndex:i] articleUrl]])
{
[_allEntries insertObject:[entries objectAtIndex:i] atIndex:0];
i++;
}
[self.tableView reloadData];
}];
}
else
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
for (RSSEntry *entry in entries)
{
[_allEntries addObject:entry];
}
NSLog(#"entries:%d", [_allEntries count]);
[self.tableView reloadData];
}];
}
}
}];
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(#"View did load");
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
target:self
action:#selector(refreshButton:)];
pauseImage = [UIImage imageNamed:#"pause_circle_small.png"];
playImage = [UIImage imageNamed:#"play_circle_small.png"];
player = nil;
isPlaying = NO;
self.title = #"Feed";
self.allEntries = [NSMutableArray array];
self.queue = [[[NSOperationQueue alloc] init] autorelease];
self.feed = [[NSString alloc] initWithString:#"http://site.org/rss/"];
[self refresh];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [_allEntries count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UILabel *mainLabel, *secondLabel;
UIButton *playBtn;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier] autorelease];
mainLabel = [[[UILabel alloc] initWithFrame:CGRectMake(42.0, 5.0, 250.0, 20.0)] autorelease];
mainLabel.tag = MAINLABEL_TAG;
mainLabel.font = [UIFont fontWithName:#"Arial-BoldMT" size:18.0];
mainLabel.textAlignment = UITextAlignmentLeft;
mainLabel.textColor = [UIColor blackColor];
mainLabel.highlightedTextColor = [UIColor whiteColor];
[cell.contentView addSubview:mainLabel];
secondLabel = [[[UILabel alloc] initWithFrame:CGRectMake(42.0, 27.0, 250.0, 15.0)] autorelease];
secondLabel.tag = SECONDLABEL_TAG;
secondLabel.font = [UIFont fontWithName:#"ArialMT" size:14.0];
secondLabel.textAlignment = UITextAlignmentLeft;
secondLabel.textColor = [UIColor colorWithRed:222.0/255.0 green:95.0/255.0
blue:199.0/255.0 alpha:1.0];
secondLabel.highlightedTextColor = [UIColor whiteColor];
[cell.contentView addSubview:secondLabel];
playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
playBtn.tag = PLAYBTN_TAG;
playBtn.frame = CGRectMake(2.0, 6.0, playImage.size.width, playImage.size.height);
[playBtn setBackgroundImage:playImage forState:UIControlStateNormal];
//[playBtn setBackgroundImage:playImage forState:UIControlStateHighlighted];
[playBtn addTarget:self action:#selector(playTapped:)
forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:playBtn];
}
else
{
mainLabel = (UILabel *)[cell.contentView viewWithTag:MAINLABEL_TAG];
secondLabel = (UILabel *)[cell.contentView viewWithTag:SECONDLABEL_TAG];
playBtn = (UIButton *)[cell.contentView viewWithTag:PLAYBTN_TAG];
}
// Alternate bg color
if (indexPath.row%2 == 0) {
UIColor *altColor = [UIColor colorWithRed:230.0/255.0 green:230.0/255.0
blue:230.0/255.0 alpha:1];
mainLabel.backgroundColor = altColor;
secondLabel.backgroundColor = altColor;
}
else
{
UIColor *altColor = [UIColor colorWithRed:255.0 green:255.0
blue:255.0 alpha:1];
mainLabel.backgroundColor = altColor;
secondLabel.backgroundColor = altColor;
}
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
NSLog(#"Entry: %#", entry);
// Manage play button
if (entry == currEntry)
{
if(isPlaying)
{
[playBtn setBackgroundImage:pauseImage forState:UIControlStateNormal];
}
else
{
[playBtn setBackgroundImage:playImage forState:UIControlStateNormal];
}
}
else
[playBtn setBackgroundImage:playImage forState:UIControlStateNormal];
mainLabel.text = entry.articleTitle;
secondLabel.text = entry.articleArtist;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
DetailView *detailViewController = [[DetailView alloc] initWithNibName:#"DetailedView" bundle:[NSBundle mainBundle]];
RSSEntry *entry = [_allEntries objectAtIndex:[indexPath row]];
[self.navigationController pushViewController:detailViewController animated:YES];
detailViewController.songTitle.text = entry.articleTitle;
detailViewController.artistName.text = entry.articleArtist;
[entry release];
[detailViewController release];
}
- (void)dealloc
{
[player release];
player = nil;
[_queue release];
_queue = nil;
[_feed release];
_feed = nil;
[_allEntries release];
_allEntries = nil;
[super dealloc];
}
#end
Please Dont release any #synthesize variable. You should only release it in dealloc method
It's a wild guess, but you don't retain the images that you get in viewDidLoad:
pauseImage = [UIImage imageNamed:#"pause_circle_small.png"];
playImage = [UIImage imageNamed:#"play_circle_small.png"];
Either use retaining property and dot syntax or send each a retain.
AHAA!!! I was setting my RSSEntry to autorelease before putting them in the _allEntries array. They were getting dealloc'd when I changed views. Don't do that. Thanks for the help everyone. That was so simple, I feel dumb now.
please don't release the self.feed and also when unload or dealloc the view at that time put delegate nil means
tableview.delegate = nil;
this one is the main thing check after this i think u don't nil the delegate of tableview.
without line where you get crash its hard to tell, but most likely you accessing some object what was dealloc'ed
most likely its here
self.feed = [[NSString alloc] initWithString:#"http://site.org/rss/music"];
[self.feed release];
you releasing objects right away, but its hard to tell without knowing if you have retained property

Parsing method was not called in NSXML parser

I was using NSXML parser for parsing but it was not calling the parser delegate methods, its shows zero error but i don't know where i made a mistake. and i need to parse attribute contents also.
Thanks in advance
Here is my xml file and code
**1.
xml file
** <ROOT_ELEMENT><RESPONSE READ_TAG="LEVEL_LIST" RESULT="" TEXT=""/><USER USER_NAME="newadmin01" TOKEN_ID="0.6864221651800831" FULL_NAME="newadmin01, newadmin01"/><DATETIME UNFORMATTED_TEXT="Aug 10 2011 5:23PM" FORMATTED_TEXT="10 Aug 17:23"/><BREADCRUMB/><LEVEL_LIST><LEVEL ID="4519" NAME="Mega Mart" CHILD_EXISTS="Y" ADD_EDIT_PRIVILEGE="Y"/></LEVEL_LIST></ROOT_ELEMENT>
**2.
.h file
**
#interface MainLevelList : UIViewController
<UITableViewDataSource, UITableViewDelegate, UINavigationControllerDelegate, UISearchBarDelegate, NSXMLParserDelegate> {
UITableView *theTableView;
UILabel *lbl_title;
UILabel *lbl_time;
NSMutableArray *mainLevelListArray;
NSXMLParser *parser;
NSMutableString *elemName;
NSMutableString *currentValueString;
}
#property (nonatomic,retain) IBOutlet UILabel *lbl_title;
#property (nonatomic,retain) IBOutlet UILabel *lbl_time;
#property (nonatomic,retain) IBOutlet UITableView *theTableView;
#property (nonatomic, retain) NSMutableArray *mainLevelListArray;
- (IBAction)onClickLeftArrow;
- (IBAction)onClickRightArrow;
#end
**
- **3. .m file
**
#implementation MainLevelList
#synthesize mainLevelListArray;
#synthesize theTableView;
#synthesize lbl_title;
#synthesize lbl_time;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization.
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
[button1 setImage:[UIImage imageNamed:#"answerBtn.png"] forState:UIControlStateNormal];
[button1 setFrame:CGRectMake(0, 0, 66, 34)];
[button1 addTarget:self action:#selector(answerBtn:) forControlEvents:UIControlEventTouchUpInside];
[button1 setTitle:#"Answer" forState:UIControlStateNormal];
UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button1];
NSMutableArray *toolBarItems = [[[NSMutableArray alloc] init] autorelease];
[toolBarItems addObject:barButtonItem];
//[self setToolbarItems:toolBarItems];
UIButton *button3 = [UIButton buttonWithType:UIButtonTypeCustom];
[button3 setImage:[UIImage imageNamed:#"btmbar_Bg.png"] forState:UIControlStateNormal];
[button3 setFrame:CGRectMake(150, 0, 66, 34)];
[button3 addTarget:self action:#selector(home:) forControlEvents:UIControlEventTouchUpInside];
[button3 setTitle:#"Home" forState:UIControlStateNormal];
UIBarButtonItem *barButtonItem2 = [[UIBarButtonItem alloc] initWithCustomView:button3];
[toolBarItems addObject:barButtonItem2];
button3.hidden = YES;
//[self setToolbarItems:toolBarItems];
UIButton *button4 = [UIButton buttonWithType:UIButtonTypeCustom];
[button4 setImage:[UIImage imageNamed:#"btmbar_Bg.png"] forState:UIControlStateNormal];
[button4 setFrame:CGRectMake(200, 0, 66, 34)];
[button4 addTarget:self action:#selector(home:) forControlEvents:UIControlEventTouchUpInside];
[button4 setTitle:#"Home" forState:UIControlStateNormal];
UIBarButtonItem *barButtonItem3 = [[UIBarButtonItem alloc] initWithCustomView:button4];
[toolBarItems addObject:barButtonItem3];
button4.hidden = YES;
UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
[button2 setImage:[UIImage imageNamed:#"nextBtn.png"] forState:UIControlStateNormal];
[button2 setFrame:CGRectMake(250, 0, 66, 34)];
[button2 addTarget:self action:#selector(home:) forControlEvents:UIControlEventTouchUpInside];
[button2 setTitle:#"Next" forState:UIControlStateNormal];
UIBarButtonItem *barButtonItem1 = [[UIBarButtonItem alloc] initWithCustomView:button2];
[toolBarItems addObject:barButtonItem1];
[self setToolbarItems:toolBarItems];
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
NSString *responseXml = [[NSString alloc] initWithString:[[NSUserDefaults standardUserDefaults] valueForKey:#"responseXml"]];
//[[NSUserDefaults standardUserDefaults] setObject:responseXml forKey:#"responseXml"];
parser = [[NSXMLParser alloc] initWithData:[responseXml dataUsingEncoding:NSUTF8StringEncoding]];
[responseXml release];
[parser setDelegate:self];
BOOL parseFlag = [parser parse];
if (parseFlag == 1)
if(debug)NSLog(#"parseFlag = YES");
else
if(debug)NSLog(#"parseFlag = NO");
UINavigationBar *bar = [self.navigationController navigationBar];
CGRect labelRect = CGRectMake(255, 12, 60, 18);
UILabel *label = [[UILabel alloc] initWithFrame:labelRect];
[bar addSubview:label];
label.text = #"ALRICK";
label.textAlignment = UITextAlignmentLeft;
label.font = [UIFont boldSystemFontOfSize:14];
label.tag = 10;
[label release];
UIButton *logOutButton = [UIButton buttonWithType:100];
[logOutButton setImage:[UIImage imageNamed:#"exitBtn.png"] forState:UIControlStateNormal];
[logOutButton addTarget:self action:#selector(logoutButtonTouched) forControlEvents:UIControlEventTouchUpInside];
[logOutButton setTitle:#"Logout" forState:UIControlStateNormal];
UIBarButtonItem* logOutItem = [[UIBarButtonItem alloc] initWithCustomView:logOutButton];
self.navigationItem.leftBarButtonItem = logOutItem;
[lbl_title setText:#"Chain"];
[lbl_title setTextColor:[UIColor whiteColor]];
NSString *date = [NSDate date];
//NSString *date = [[NSDate date] initWithFormat:#"EEE, MMM, h:mm"];
NSLog(#"date:%#",date);
[lbl_time setText:[NSString stringWithFormat:#"%#",date]];
[lbl_time setTextColor:[UIColor whiteColor]];
mainLevelListArray = [[NSMutableArray alloc] init];
//[tableData addObject:#"ICA"];
// [tableData addObject:#"Bread"];
// [tableData addObject:#"ISF"];
// [tableData addObject:#"OSF"];
// [tableData addObject:#"BBC"];
// [tableData addObject:#"ACC"];
// [tableData addObject:#"CFF"];
}
-(void)answerBtn:(id)sender {
QuestionnaireListView *m_questionnaireList = [[QuestionnaireListView alloc] initWithNibName:#"QuestionnaireListView" bundle:nil];
[self.navigationController pushViewController:m_questionnaireList animated:YES];
[m_questionnaireList release];
}
- (void)logoutButtonTouched {
[self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)onClickLeftArrow {
//[self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)onClickRightArrow {
//[self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidUnload {
[super viewDidUnload];
}
- (void)dealloc {
[super dealloc];
[mainLevelListArray release];
}
#pragma mark - UITableView delegate methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [mainLevelListArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *kCustomCellID = #"MyCellID";
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:kCustomCellID];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCustomCellID] autorelease];
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.textLabel.text = [mainLevelListArray objectAtIndex:indexPath.row];
UIView *m_view = [[[UIView alloc] init] autorelease];
m_view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"listHighlight_bg.png"]];
cell.selectedBackgroundView = m_view;
return cell;
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
NSLog(#"element Name = %#", elementName);
NSLog(#"namespace URI = %#", namespaceURI);
NSLog(#"qualified Name = %#", qName);
NSLog(#"attributeDict = %#", attributeDict);
elemName = [[NSString alloc] initWithString:elementName];
attributeDict = [[NSString alloc] initWithString:[attributeDict objectForKey:#"READ_TAG"]];
//attribute = [attributeDict objectForKey:#"READ_TAG"];
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if ([elemName isEqualToString:#"RESPONSE"]) {
if (!currentValueString) {
currentValueString = [[NSMutableString alloc] initWithCapacity:1024];
}
[currentValueString appendString:string];
}
else if ([elemName isEqualToString:#"USER"]) {
if (!currentValueString) {
currentValueString = [[NSMutableString alloc] initWithCapacity:1024];
}
[currentValueString appendString:string];
}
if ([elemName isEqualToString:#"DATETIME"]) {
if (!currentValueString) {
currentValueString = [[NSMutableString alloc] initWithCapacity:1024];
}
[currentValueString appendString:string];
}
else if ([elemName isEqualToString:#"BREADCRUMB"]) {
if (!currentValueString) {
currentValueString = [[NSMutableString alloc] initWithCapacity:1024];
}
[currentValueString appendString:string];
}
else if ([elemName isEqualToString:#"LEVEL"]) {
if (!currentValueString) {
currentValueString = [[NSMutableString alloc] initWithCapacity:1024];
}
[currentValueString appendString:string];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if ([elemName isEqualToString:#"RESPONSE"]) {
[mainLevelListArray addObject:currentValueString];
[currentValueString release];
currentValueString = nil;
[elemName release];
elemName = nil;
}
else if ([elemName isEqualToString:#"USER"]) {
[mainLevelListArray addObject:currentValueString];
[currentValueString release];
currentValueString = nil;
[elemName release];
elemName = nil;
}
else if ([elemName isEqualToString:#"DATETIME"]) {
[mainLevelListArray addObject:currentValueString];
[currentValueString release];
currentValueString = nil;
[elemName release];
elemName = nil;
}
else if ([elemName isEqualToString:#"BREADCRUMB"]) {
[mainLevelListArray addObject:currentValueString];
[currentValueString release];
currentValueString = nil;
[elemName release];
elemName = nil;
}
else if ([elemName isEqualToString:#"LEVEL"]) {
[mainLevelListArray addObject:currentValueString];
[currentValueString release];
currentValueString = nil;
[elemName release];
elemName = nil;
}
}
#end
**
add few lines in viewDidLoad method as given below
(void)viewDidLoad {
[super viewDidLoad];
//NSMutableString *urlString ; //assign url string
NSString *postLength = [NSString stringWithFormat:#"%d", [urlString length]];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[urlString dataUsingEncoding:NSUTF8StringEncoding]];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//write your rest part of viewDidLoad
}
Please check the encoding scheme in xml which you are getting from server side as a response and check your iPhone client code it's UTF8, UTF16 or something else.

how to select multiple data from multiple rows in custom cell in xcode?

code:
check it:
#import <UIKit/UIKit.h>
#interface addsymptom : UITableViewController<UITableViewDelegate, UITableViewDataSource> {
NSMutableArray *listData;
}
#property(nonatomic,retain)NSMutableArray *listData;
#end
data.m:
============
#import "CustomCell.h"
#implementation addsymptom
#synthesize listData;
- (void)viewDidLoad
{
self.navigationItem.title= #"Symptoms";
self.view.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:#"mainbg.png"]];
listData =[[NSMutableArray alloc] init];
[listData addObject:#"Backpain"];
[listData addObject:#"headache"];
[listData addObject:#"vomitting"];
[listData addObject:#"Bodypain"];
[listData addObject:#"thursday"];
[listData addObject:#"maleria"];
[listData addObject:#"Food poisioning"];
UIBarButtonItem *saveButton=[[UIBarButtonItem alloc]initWithTitle:#"save"
style:UIBarButtonSystemItemDone
target:self
action:#selector(save)];
self.navigationItem.rightBarButtonItem = saveButton;
[saveButton release];
[super viewDidLoad];
}
-(void)save {
[self.navigationController popViewControllerAnimated:YES];
}
- (UITableViewCell *)tableView:(UITableView *) tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CustomCell";
CustomCell *cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"CustomCell" owner:self options:nil];
for (id currentObject in topLevelObjects){
if ([currentObject isKindOfClass:[UITableViewCell class]]){
cell = (CustomCell *) currentObject;
break;
}
}
}
cell.textLabel.text = [listData objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc. that aren't in use.
}
- (void)viewDidUnload
{
self.listData = nil;
}
- (void)dealloc
{
[super dealloc];
}
#end
custom cell.h:
==========
#import <Foundation/Foundation.h>
#interface CustomCell :UITableViewCell {
IBOutlet UILabel *textLabel;
IBOutlet UIButton *bttn;
BOOL isChecked;
NSString *ans;
}
#property (nonatomic,retain) IBOutlet UILabel *textLabel;
#property (nonatomic,assign) BOOL isChecked;
#property(nonatomic,assign)IBOutlet UIButton *bttn;
-(void)checkBoxClicked:(id)sender;
#end
customcell.m:
==============
#import "CustomCell.h"
#implementation CustomCell
#synthesize textLabel,bttn,isChecked;
-(id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithFrame:frame ]) {
textLabel = [[UILabel alloc]init];
textLabel.textAlignment = UITextAlignmentLeft;
}
return self;
}
NSString *ABC=NULL;
NSString *xyz=NULL;
-(void)checkBoxClicked:(id)sender{
UIButton *tappedButton = (UIButton*)sender;
if([tappedButton.currentImage isEqual:[UIImage imageNamed:#"NotSelected.png"]]) {
[sender setImage:[UIImage imageNamed: #"IsSelected.png"] forState:UIControlStateNormal];
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"Message"
message:textLabel.text
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil,nil]autorelease];
[alert show];
ans = textLabel.text;
NSLog(#"%#",ans);
}
else {
[sender setImage:[UIImage imageNamed:#"NotSelected.png"]forState:UIControlStateNormal];
}
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
}
- (void)dealloc {
[super dealloc];
}
#end
check this example it has some implementation like yours
http://cocoawithlove.com/2009/01/multiple-row-selection-and-editing-in.html
best of luck
//CustomCell.h
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#interface CustomCell :UITableViewCell {
IBOutlet UILabel *textLabel;
IBOutlet UIButton *bttn;
BOOL isChecked;
NSString *ans;
}
#property (nonatomic,retain) IBOutlet UILabel *textLabel;
#property (nonatomic,assign) BOOL isChecked;
#property(nonatomic,assign)IBOutlet UIButton *bttn;
//-(void)checkBoxClicked:(id)sender;
#end
//CustomCell.m
#import "CustomCell.h"
#implementation CustomCell
#synthesize textLabel,bttn,isChecked;
-(id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithFrame:frame ]) {
textLabel = [[UILabel alloc]init];
textLabel.textAlignment = UITextAlignmentLeft;
}
return self;
}
NSString *ABC=NULL;
NSString *xyz=NULL;
//-(void)checkBoxClicked:(id)sender{
//
// UIButton *tappedButton = (UIButton*)sender;
//
//
// if([tappedButton.currentImage isEqual:[UIImage imageNamed:#"chkbox_unckd.png"]]) {
// [sender setImage:[UIImage imageNamed: #"chkbox_ckd.png"] forState:UIControlStateNormal];
// UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"Message"
// message:textLabel.text
// delegate:self
// cancelButtonTitle:#"OK"
// otherButtonTitles:nil,nil]autorelease];
// [alert show];
//
// ans = textLabel.text;
//
//
// NSLog(#"%#",ans);
//
//
// }
//
// else {
// [sender setImage:[UIImage imageNamed:#"chkbox_unckd.png"]forState:UIControlStateNormal];
// }
//
//
//
//}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
// [bttn setImage:[UIImage imageNamed:#"chkbox_ckd.png"] forState:UIControlStateNormal];
[super setSelected:selected animated:animated];
}
- (void)dealloc {
[super dealloc];
}
#end
//addsymptom.h
#import <UIKit/UIKit.h>
#interface addsymptom : UIViewController<UITableViewDelegate, UITableViewDataSource> {
NSMutableArray *listData;
IBOutlet UITableView *table;
NSMutableArray *TitlesArray;
NSMutableArray *isCheckedArr;
}
#property(nonatomic,retain)NSMutableArray *listData;
- (void)saveTheChanges;
#end
//addsymptom.m
#import "addsymptom.h"
#import "CustomCell.h"
#implementation addsymptom
#synthesize listData;
- (void)viewDidLoad
{
self.navigationItem.title= #"Symptoms";
self.view.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:#"mainbg.png"]];
listData =[[NSMutableArray alloc] init];
[listData addObject:#"Backpain"];
[listData addObject:#"headache"];
[listData addObject:#"vomitting"];
[listData addObject:#"Bodypain"];
[listData addObject:#"thursday"];
[listData addObject:#"maleria"];
[listData addObject:#"Food poisioning"];
UIBarButtonItem *saveButton=[[UIBarButtonItem alloc]initWithTitle:#"save" style:UIBarButtonSystemItemDone target:self action:#selector(saveTheChanges)];
isCheckedArr = [[NSMutableArray alloc] init];
for (int i=0; i<[listData count]; i++) {
[isCheckedArr addObject:#"0"];
}
self.navigationItem.rightBarButtonItem = saveButton;
[saveButton release];
TitlesArray = [[NSMutableArray alloc] init];
}
-(void)save {
[self.navigationController popViewControllerAnimated:YES];
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [listData count];
}
- (UITableViewCell *)tableView:(UITableView *) tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CustomCell";
CustomCell *cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"CustomCell" owner:self options:nil];
for (id currentObject in topLevelObjects){
if ([currentObject isKindOfClass:[UITableViewCell class]]){
cell = (CustomCell *) currentObject;
break;
}
}
}
cell.textLabel.text = [listData objectAtIndex:indexPath.row];
[cell.bttn setTag:indexPath.row];
[cell.bttn addTarget:self action:#selector(updateCheckbox:) forControlEvents:UIControlEventTouchUpInside];
if ([[isCheckedArr objectAtIndex:indexPath.row] isEqualToString:#"1"])
{
[cell.bttn setImage:[UIImage imageNamed:#"chkbox_ckd.png"] forState:UIControlStateNormal];
}
else
{
[cell.bttn setImage:[UIImage imageNamed:#"chkbox_unckd.png"] forState:UIControlStateNormal];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
- (void)updateCheckbox:(id)sender {
if ([[isCheckedArr objectAtIndex:[sender tag]] isEqualToString:#"0"]) {
[isCheckedArr replaceObjectAtIndex:[sender tag] withObject:#"1"];
}
else if ([[isCheckedArr objectAtIndex:[sender tag]] isEqualToString:#"1"]) {
[isCheckedArr replaceObjectAtIndex:[sender tag] withObject:#"0"];
for (int i=0; i<[TitlesArray count]; i++) {
if ([[listData objectAtIndex:[sender tag]] isEqualToString:[TitlesArray objectAtIndex:i]]) {
[TitlesArray removeObjectAtIndex:i];
}
}
}
[table reloadData];
}
- (void)saveTheChanges {
for (int i=0; i<[isCheckedArr count]; i++) {
if ([[isCheckedArr objectAtIndex:i] isEqualToString:#"1"]) {
for (int j=0; j<[TitlesArray count]; j++) {
if ([[listData objectAtIndex:i] isEqualToString:[TitlesArray objectAtIndex:j]]) {
[TitlesArray removeObjectAtIndex:j];
}
}
[TitlesArray addObject:[listData objectAtIndex:i]];
}
}
for (int i=0; i<[TitlesArray count]; i++) {
NSLog(#"%#",[TitlesArray objectAtIndex:i]);
}
NSLog(#"=======");
}
- (void)viewDidUnload
{
// self.listData = nil;
}
- (void)dealloc
{
[listData release];
[TitlesArray release];
[isCheckedArr release];
[super dealloc];
}
#end
Does this post help, if you want Mail app style multiple selection of cells? Another post with great answers.