Add Item into a a tableView ?! - xcode

Hi I'm trying to create a dynamic tableView by the following method. But I'm getting an error during execution of the simulator. it works with a pre declared NSArray, but the following method doesn't work. Could you please help me on this topic ?
NSMutableArray *mesProduits;
mesProduits = [[NSMutableArray alloc] init];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellule];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:cellule];
}
for(int index = 0; index < [myObjectsFormulas count]; index = index+13)
{
monTest = [myObjectsFormulas objectAtIndex:monIndex];
monIndex = monIndex+13;
[mesProduits addObject:monTest];
}
NSString *celltext1 = [mesProduits objectAtIndex:indexPath.row];
cell.textLabel.text = celltext1;

I believe this is your cellForRowAtIndexPath method then do like following:
// Declare mesProduits as a property
- (void) viewDidLoad {
// Initialize and assigned values to monIndex and myObjectsFormulas
self.mesProduits = [[NSMutableArray alloc] init];
for(int index = 0; index < [myObjectsFormulas count]; index = index+13)
{
monTest = [myObjectsFormulas objectAtIndex:monIndex];
monIndex = monIndex+13;
[self.mesProduits addObject:monTest];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellule];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:cellule];
}
NSString *celltext1 = [self.mesProduits objectAtIndex:indexPath.row];
cell.textLabel.text = celltext1;
}

Related

How to search NSMutableArray with UISearchBar?

I've searched many places but could not find the answer, so I decided to set my own question.
I populate a UITableView with data from JSON. My data structure is like this:
NSMutableArray* studentList = [(NSDictionary*)[responseString JSONValue] objectForKey:#"StudentList"];
JSON:
{
"StudentList":[
{
"StudentID":"08DH11039",
"StudentFirstName":"Nguyen Lam",
"StudentLastName":"Binhh"
},
{
"StudentID":"08DH11163",
"StudentFirstName":"Nguyen Minh",
"StudentLastName":"Duc"
},
{
"StudentID":"08DH11038",
"StudentFirstName":"Nguyen Bao",
"StudentLastName":"Khuyen"
},
{
"StudentID":"08DH11037",
"StudentFirstName":"Nguyen Tran Duy",
"StudentLastName":"Phuong"
}
]
}
Add data to UITableView:
- (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];
}
NSDictionary *student = [studentList objectAtIndex:indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:#"%d. %# %#", indexPath.row+1, [student objectForKey:#"StudentFirstName"], [student objectForKey:#"StudentLastName"]];
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:15];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
I also add a UISearchBar but it didn't work:
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[searchData removeAllObjects];
NSArray *student;
for(student in studentListCopy) //take the n group (eg. group1, group2, group3)
{
NSLog(#"%#", student);
NSMutableArray *newGroup = [[NSMutableArray alloc] init];
NSString *element;
for(element in student)
NSRange range = [element rangeOfString:searchString
options:NSCaseInsensitiveSearch];
if (range.length > 0) { //if the substring match
[newGroup addObject:element]; //add the element to group
}
}
if ([newGroup count] > 0) {
[searchData addObject:newGroup];
}
}
return YES;
}
Please help me to get it work. I want to search FirstName or LastName, which are displayed in TableView.
I'm new to iOS programming. Thank you very much.
I think this will be useful to you for understanding how the NSMutableArray is used with a UISearchBar and UITableView. The Example which I got from the internet is here. Maybe this will help you in solving your problem

Invalid index path for use with UITableView when selecting rows beyond a certain number

- (int)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection: (NSInteger)section
{
return #"Substitutes";
}
- (int)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
int cnt=[subArray count];
return [subArray count];
}
- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSArray *visible = [tableView indexPathsForVisibleRows];
NSIndexPath *indexpath = (NSIndexPath*)[visible objectAtIndex:0];
if ((selectedIndexPath != nil) && (selectedIndexPath.row == indexPath.row)){
NSUInteger row = [indexPath row];
NSString *subtitle =[[subArray objectAtIndex:row] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString *subDet =[[subDetArray objectAtIndex:row] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
int height = [self heightOfCellWithTitle:subtitle andSubtitle:subDet];
return(height < CONST_Cell_height ? CONST_Cell_height : height);
}
return 40.0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger row = [indexPath row];
static NSString *CellIdentifier = #"SearchCell";
UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
if ((selectedIndexPath != nil) && (selectedIndexPath.row == indexPath.row)){
cell = [self CreateMultilinesCell:CellIdentifier];
cell.textLabel.text=[[subArray objectAtIndex:row] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
cell.detailTextLabel.text =[[subDetArray objectAtIndex:row] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
return cell;
} else {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
cell.textLabel.text=[[subArray objectAtIndex:row] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
cell.detailTextLabel.text =[[subDetArray objectAtIndex:row] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
return cell;
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (selectedIndexPath == indexPath) {
selectedIndexPath = nil;
[table reloadData];
} else {
selectedIndexPath = indexPath;
//static NSString *CellIdentifier = #"Cell";
//UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
//cell.textLabel.text=#"test";
//cell.detailTextLabel.text =#"det Test";
[table reloadData];
}
[self.table deselectRowAtIndexPath : indexPath animated : NO];
[tableView beginUpdates];
[tableView endUpdates];
}
i implemented table view using above code.when i selecting row no. 26 v or more it
expands on selection but doesn't contract on next click.& gives me error on scroll
NSInternalInconsistencyException', reason: 'Invalid index path for use with UITableView. Index paths passed to table view must contain exactly two indices specifying the section and row. Please use the category on NSIndexPath in UITableView.h if possible.'
code work smoothly for 25 rows. where i went wrong?
i got it finaly.:) selectedIndexpath gives garbage. i replace it by self.selectedIndexpath.
i didnt get why it do so on record no. 25 onwards.But this worked for me
Use like this
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:sender.tag-1 inSection:0];
CGRect rectOfCellInTableView = [objTableView rectForRowAtIndexPath:indexPath];
CGRect rectOfCellInSuperview = [objTableView convertRect:rectOfCellInTableView toView:[objTableView superview]];

UItableView , remove and add rows by begin/end Upradates

HI i have some piece of code with table and some items in it.
i'd like to u advise me, how to remove and add some rows with animation.
When user scroll down to the last row "show next 5 item" code should to detect it and last row was removed and next 5 item will showed.
how to detect that table was scrolled to the bottom.
#import "tableAddRemoveViewController.h"
#implementation tableAddRemoveViewController
#synthesize myTable, listOfItems;
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
next5item = [[NSArray alloc] initWithObjects:#"next Item1", #"next Item2", #"next Item3", #"next Item4", #"next Item5", nil];
[self showItems];
[super viewDidLoad];
}
- (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 = [listOfItems objectAtIndex:indexPath.row];
return cell;
}
-(void) showItems
{
NSLog(#"Button Pressed");
listOfItems = [[NSMutableArray alloc] initWithObjects:#"item1", #"item2", #"item3", #"item4", #"item5", #"item6", #"item7", #"item8", #"item9", #"item10", #"item11", #"item12", #"item13", #"item14", #"item15",#"show next 5 items", nil];
NSMutableArray *indexPathsToInsert = [[NSMutableArray alloc] init];
for (NSInteger i = 0; i < [listOfItems count]; i++) {
[indexPathsToInsert addObject:[NSIndexPath indexPathForRow:i inSection:0]];
}
[myTable beginUpdates];
[myTable insertRowsAtIndexPaths:indexPathsToInsert withRowAnimation:UITableViewRowAnimationLeft];
[myTable endUpdates];
}
-(void) removeLastRow
{
NSLog(#"removeLastRow");
}
#end
thx

How to solve slow scrolling in UITableView - using the YouTube API

I'm working with the google YouTube API, and I'm using this code found here http://pastebin.com/vmV2c0HT
The Code that slows things down is this one here
cell.imageView.image = [UIImage imageWithData:data];
When I remove that code it scrolls smoothly. Any idea on how I can go about having it load the images from google but still scroll smoothly? I've read some of the answers on loading images in a different way, but I still can't figure out how I'll make that work with the code I'm using.
Any help will be appreciated.
Bellow is the full code.
#import "RootViewController.h"
#interface RootViewController (PrivateMethods)
- (GDataServiceGoogleYouTube *)youTubeService;
#end
#implementation RootViewController
#synthesize feed;
- (void)viewDidLoad {
NSLog(#"loading");
GDataServiceGoogleYouTube *service = [self youTubeService];
NSString *uploadsID = kGDataYouTubeUserFeedIDUploads;
NSURL *feedURL = [GDataServiceGoogleYouTube youTubeURLForUserID:#"BmcCarmen"
userFeedID:uploadsID];
[service fetchFeedWithURL:feedURL
delegate:self
didFinishSelector:#selector(request:finishedWithFeed:error:)];
[super viewDidLoad];
}
- (void)request:(GDataServiceTicket *)ticket
finishedWithFeed:(GDataFeedBase *)aFeed
error:(NSError *)error {
self.feed = (GDataFeedYouTubeVideo *)aFeed;
[self.tableView reloadData];
}
#pragma mark Table view methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [[feed entries] count];
}
// Customize the appearance of table view cells.
- (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];
}
// Configure the cell.
GDataEntryBase *entry = [[feed entries] objectAtIndex:indexPath.row];
NSString *title = [[entry title] stringValue];
NSArray *thumbnails = [[(GDataEntryYouTubeVideo *)entry mediaGroup] mediaThumbnails];
cell.textLabel.text = title;
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[thumbnails objectAtIndex:0] URLString]]];
cell.imageView.image = [UIImage imageWithData:data];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 100.0f;
}
- (void)dealloc {
[super dealloc];
}
- (GDataServiceGoogleYouTube *)youTubeService {
static GDataServiceGoogleYouTube* _service = nil;
if (!_service) {
_service = [[GDataServiceGoogleYouTube alloc] init];
[_service setShouldCacheDatedData:YES];
[_service setServiceShouldFollowNextLinks:YES];
}
// fetch unauthenticated
[_service setUserCredentialsWithUsername:nil
password:nil];
return _service;
}
#end
GCD is a wonderful thing. Here is what I do:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"youTubeCell";
UITableViewCell *cell = nil;
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell.
GDataEntryBase *entry = [[feed entries] objectAtIndex:indexPath.row];
NSString *title = [[entry title] stringValue];
NSArray *thumbnails = [[(GDataEntryYouTubeVideo *)entry mediaGroup] mediaThumbnails];
cell.textLabel.text = title;
// Load the image with an GCD block executed in another thread
dispatch_queue_t downloadQueue = dispatch_queue_create("image downloader", NULL);
dispatch_async(downloadQueue, ^{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[thumbnails objectAtIndex:0] URLString]]];
UIImage * image = [UIImage imageWithData:data];
dispatch_async(dispatch_get_main_queue(), ^{
cell.imageView.image = image;
cell.imageView.contentMode = UIViewContentModeScaleAspectFit;
[cell setNeedsLayout];
});
});
dispatch_release(downloadQueue);
return cell;
}
Scrolling is now super smooth. The only drawback is that when you scroll quickly, cells are re-used and sometimes the images change as new ones come in.

all images in table view are the same in iPhone app

I have a table view where I want a different image for each cell based on logic. Here is my cellforrowatindexpath code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = #"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:MyIdentifier] autorelease];
}
NSInteger *row = [indexPath row];
NSString *platform = [[myStringArray objectAtIndex: row];
cell.imageView.image = [self imageForInventory:platform];
return cell;
}
Here is my imageForInventory method:
- (UIImage *)imageForInventory:(NSString *)platform {
if (platform = #"Win") {
UIImage *winImage = [UIImage imageNamed:#"Vista.png"];
return winImage;
}else if (platform = #"Mac") {
UIImage *appleImage = [UIImage imageNamed:#"Apple.png"];
return appleImage;
}else if (platform = #"Linux") {
UIImage *linuxImage = [UIImage imageNamed:#"Linux.png"];
return linuxImage;
}
return nil;
}
This shows the winImage for every row ignoring the if statements. How do I get the image to set accordingly per cell?
It's probably your comparison code, to compare strings in imageForInventory use [str1 isEqualToString:str2]. You're using = which is the assignment operator right now, but even if you change it to == it wouldn't work.

Resources