I have a problem in getting a method to work, and I am totally confused.
I am unable to hand over a string as a variable for my method.
I call the function even with the string, no variable currently.
Engine *myEngine = [Engine sharedInstance];
[myEngine getContentArrayFromEngine:#"zumbra"];
My method
-(NSMutableArray*) getContentArrayFromEngine:(NSString *)catName{
NSMutableSet* categorieContent = [[NSMutableSet alloc] init];
NSLog(#"Catname:%#", catName);
//some more code
}
NSLOG output
2011-12-18 18:49:44.165 Zitate[77224:15203] Catname:(null)
Why is catName empty ???
edit1: the complete code
ThirdViewController.m
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
NSString* myTempCatname;
myTempCatname = cell.textLabel.text;
// NSLog(#"test select %#", myTempCatname);
DetailViewController *detailVC = [self.storyboard instantiateViewControllerWithIdentifier:#"detailzitat"];
[self.navigationController pushViewController:detailVC animated:YES];
Engine *myEngine = [Engine sharedInstance];
[myEngine getContentArrayFromEngine:myTempCatname];
}
and in the engine.m
-(NSMutableArray*) getContentArrayFromEngine:(NSString *)catName{
NSMutableSet* categorieContent = [[NSMutableSet alloc] init];
NSLog(#"Übergebener Catname:%#", catName);
// catName=#"zumbra";
// NSLog(#"Inhalt InhalteFromWeb:%#", InhalteFromWeb);
NSLog(#"Catname:%#", catName);
unsigned count = [InhalteFromWeb count];
while (count--) {
NSLog(#"count %d %#", count, [[InhalteFromWeb objectAtIndex:count] objectForKey:CATEGORY]);
if([[[InhalteFromWeb objectAtIndex:count] objectForKey:CATEGORY] isEqualToString:catName]) {
[categorieContent addObject:[InhalteFromWeb objectAtIndex:count]];
NSLog(#"Row %d has Content%#",count, [InhalteFromWeb objectAtIndex:count]);
}
}
NSLog(#"Inhalt Category:%#", categorieContent);
NSArray* tempAr = [[NSArray alloc] initWithArray:[categorieContent allObjects]];
return [NSMutableArray arrayWithArray:tempAr];
}
EDIT2:
Ok, even the hint with the catName did not work. so I have changed my code a little bit.
I have an array with a category, title, content, author, image for each row
I would like to do two things
1) get a unique list of all categories (its working fine)
2) when tapping on one of these categories , open a detailView , show the first element of this category, jump to previous and next item in category by swiping around.
For this, I am going to SET the category I have chosen
First try was to handover in the method, which did not work.
Now I though, SET the category in my engine.h and when displaying the single item, get the array for this category back.
but again, the value of the category is not stored.
ThirdViewController.h
#import <UIKit/UIKit.h>
#import "SecondViewController.h"
#interface ThirdViewController : UIViewController<UITableViewDelegate, UITableViewDataSource> {
NSMutableArray* CategoryList;
}
#property (nonatomic, retain) NSMutableArray* CategoryList;
#end
ThirdViewController.m
#import "ThirdViewController.h"
#import "engine.h"
#import "DetailViewController.h"
#implementation ThirdViewController
#synthesize CategoryList;
- (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.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
Engine *myEngine = [Engine sharedInstance];
CategoryList = [myEngine getCategories];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [CategoryList count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier =#"Cell";
UITableViewCell *cell = (UITableViewCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [CategoryList objectAtIndex:indexPath.row];
return cell;
}
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
NSString* myTempCatname;
myTempCatname = cell.textLabel.text;
DetailViewController *detailVC = [self.storyboard instantiateViewControllerWithIdentifier:#"detailzitat"];
[self.navigationController pushViewController:detailVC animated:YES];
Engine *myEngine = [Engine sharedInstance];
[myEngine setCategName:myTempCatname];
NSLog(#"Aufruf %#", myTempCatname);
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
DetailViewController.h
#import <UIKit/UIKit.h>
#import <MessageUI/MFMailComposeViewController.h>
#import "engine.h"
#interface DetailViewController : UIViewController<MFMailComposeViewControllerDelegate> {
IBOutlet UILabel *authorLabel;
IBOutlet UILabel *categoryLabel;
IBOutlet UILabel *titleLabel;
IBOutlet UITextView *contentTextView;
NSString *authorText, *contentText, *categoryText, *titleText, *imageText, *catName;
NSMutableArray *contentArray;
}
#property (nonatomic, retain) IBOutlet UITextView *contentTextView;
#property (nonatomic, retain) IBOutlet UILabel *authorLabel;
#property (nonatomic, retain) IBOutlet UILabel *categoryLabel;
#property (nonatomic, retain) IBOutlet UILabel *titleLabel;
#property (nonatomic, retain) NSString *authorText, *contentText, *categoryText, *titleText, *imageText, *catName;
#property (nonatomic, retain) NSMutableArray *contentArray;
-(IBAction)vorher:(id)sender;
-(IBAction)nachher:(id)sender;
#end
DetailViewController.m
#import "DetailViewController.h"
#implementation DetailViewController
#synthesize contentTextView;
#synthesize authorText, contentText, categoryText, titleText, imageText;
#synthesize authorLabel, categoryLabel, titleLabel;
#synthesize contentArray;
#synthesize catName;
int contentIndex;
int contentMax;
- (IBAction)swipeDetected:(UIGestureRecognizer *)sender {
NSLog(#"Right Swipe detected");
}
-(IBAction) vorher:(id)sender {
NSLog(#"-----VORHER Button gedrückt-------");
if (contentIndex==0) {contentIndex=contentMax-1;}
else {contentIndex--;}
titleText = [[contentArray objectAtIndex:contentIndex] objectForKey:TITLE];
authorText= [[contentArray objectAtIndex:contentIndex] objectForKey:AUTHOR];
contentText= [[contentArray objectAtIndex:contentIndex] objectForKey:CONTENT];
authorLabel.text=authorText;
titleLabel.text=titleText;
contentTextView.text=contentText;
}
-(IBAction) nachher:(id)sender {
NSLog(#"-----Nachher Button gedrückt-------");
if (contentIndex==contentMax-1) {contentIndex=0;}
else {contentIndex++;}
titleText = [[contentArray objectAtIndex:contentIndex] objectForKey:TITLE];
authorText= [[contentArray objectAtIndex:contentIndex] objectForKey:AUTHOR];
contentText= [[contentArray objectAtIndex:contentIndex] objectForKey:CONTENT];
authorLabel.text=authorText;
titleLabel.text=titleText;
contentTextView.text=contentText;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
Engine *myEngine = [Engine sharedInstance];
contentArray = [myEngine getContentArrayFromEngine];
contentMax = [contentArray count];
UISwipeGestureRecognizer *swipeRecognizerRight =
[[UISwipeGestureRecognizer alloc]
initWithTarget:self
action:#selector(vorher:)];
swipeRecognizerRight.direction = UISwipeGestureRecognizerDirectionRight;
[self.view addGestureRecognizer:swipeRecognizerRight];
UISwipeGestureRecognizer *swipeRecognizerLeft =
[[UISwipeGestureRecognizer alloc]
initWithTarget:self
action:#selector(nachher:)];
swipeRecognizerLeft.direction = UISwipeGestureRecognizerDirectionLeft;
[self.view addGestureRecognizer:swipeRecognizerLeft];
titleText = [[contentArray objectAtIndex:contentIndex] objectForKey:TITLE];
authorText= [[contentArray objectAtIndex:contentIndex] objectForKey:AUTHOR];
contentText= [[contentArray objectAtIndex:contentIndex] objectForKey:CONTENT];
authorLabel.text=authorText;
titleLabel.text=titleText;
contentTextView.text=contentText;
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
engine.h
//#import
#define AUTHOR #"author"
#define CATEGORY #"cat"
#define CONTENT #"content"
#define IMAGE #"image"
#define TITLE #"title"
#interface Engine : NSObject {
NSMutableArray* InhalteFromWeb;
NSInteger maxAnzahlInhalte;
NSString* categNameStorage;
}
+ (Engine *) sharedInstance;
- (NSMutableArray*) getZitateArrayFromEngine;
- (NSInteger) getMaxAnzahlZitateFromEngine;
- (NSString*) getAutor:(NSInteger)pos;
- (NSString*) getZitat:(NSInteger)pos;
- (NSString*) getAuthor:(NSInteger)pos;
- (NSString*) getCategory:(NSInteger)pos;
- (NSString*) getContent:(NSInteger)pos;
- (NSString*) getImage:(NSInteger)pos;
- (NSString*) getTitle:(NSInteger)pos;
-(NSMutableArray*) getContentArrayFromEngine;
-(void) setCategName:(NSString *) categNameVariable;
-(NSString*) getCategName;
-(NSMutableArray*) getCategories;
#end
engine.m
#import "Engine.h"
#implementation Engine
static Engine *_sharedInstance;
- (id) init
{
if (self = [super init])
{
// custom initialization
//Beginn my code
NSURL *url = [NSURL URLWithString:#"http://www.*/iMotivate.plist"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection )
{
InhalteFromWeb = [[NSMutableArray alloc] initWithContentsOfURL:url];
maxAnzahlInhalte = [InhalteFromWeb count];
}
else
{
NSLog(#"Connection failed");
}
}
return self;
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// NSLog(#"Recieving Response...");
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// NSLog(#"Recieving Data...");
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message : #"An error has occured.Please verify your internet connection."
delegate:nil
cancelButtonTitle :#"OK"
otherButtonTitles :nil];
[alert show];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// NSLog(#"DONE. Received Quotes: %d", maxAnzahlZitate);
}
// ###########
+ (Engine *) sharedInstance
{
if (!_sharedInstance)
{
_sharedInstance = [[Engine alloc] init];
}
return _sharedInstance;
}
// Getter and Setter for WebArray
- (NSMutableArray*) getZitateArrayFromEngine{
return InhalteFromWeb;
}
- (NSInteger) getMaxAnzahlZitateFromEngine{
return maxAnzahlInhalte;
}
- (NSString*) getAutor:(NSInteger)pos{
return [[InhalteFromWeb objectAtIndex:pos] objectForKey:AUTHOR];
}
- (NSString*) getZitat:(NSInteger)pos{
return [[InhalteFromWeb objectAtIndex:pos] objectForKey:CONTENT];
}
// #######
- (NSString*) getAuthor:(NSInteger)pos{
return [[InhalteFromWeb objectAtIndex:pos] objectForKey:AUTHOR];
}
- (NSString*) getCategory:(NSInteger)pos{
return [[InhalteFromWeb objectAtIndex:pos] objectForKey:CATEGORY];
}
- (NSString*) getContent:(NSInteger)pos{
return [[InhalteFromWeb objectAtIndex:pos] objectForKey:CONTENT];
}
- (NSString*) getImage:(NSInteger)pos{
return [[InhalteFromWeb objectAtIndex:pos] objectForKey:IMAGE];
}
- (NSString*) getTitle:(NSInteger)pos{
return [[InhalteFromWeb objectAtIndex:pos] objectForKey:TITLE];
}
-(NSArray*) getCategories {
NSMutableSet* categorieSet = [[NSMutableSet alloc] init];
unsigned count = [InhalteFromWeb count];
while (count--) {
NSString *tempString;
tempString=[[InhalteFromWeb objectAtIndex:count] objectForKey:CATEGORY];
// NSLog(#"tempString %#", tempString );
[categorieSet addObject:tempString];
}
// NSLog(#"categories from engine %#", categorieSet);
NSArray* tempAr = [[[NSArray alloc] initWithArray:[categorieSet allObjects]]sortedArrayUsingSelector:#selector(caseInsensitiveCompare:)];
return [NSMutableArray arrayWithArray:tempAr];
}
-(void) setCategName:(NSString *) categNameVariable
{ NSLog(#"categNameStorage 2%#",categNameStorage);
categNameStorage=categNameVariable;
NSLog(#"setCategName 1 %#",categNameVariable);
NSLog(#"categNameStorage 2%#",categNameStorage);
}
-(NSString*) getCategName {
return categNameStorage;
}
-(NSMutableArray*) getContentArrayFromEngine{
NSMutableSet* categorieContent = [[NSMutableSet alloc] init];
NSLog(#"Übergebener Catname:%#", categNameStorage);
// NSLog(#"Inhalt InhalteFromWeb:%#", InhalteFromWeb);
unsigned count = [InhalteFromWeb count];
while (count--) {
// NSLog(#"count %d %#", count, [[InhalteFromWeb objectAtIndex:count] objectForKey:CATEGORY]);
if([[[InhalteFromWeb objectAtIndex:count] objectForKey:CATEGORY] isEqualToString:categNameStorage]) {
[categorieContent addObject:[InhalteFromWeb objectAtIndex:count]];
// NSLog(#"Row %d has Content%#",count, [InhalteFromWeb objectAtIndex:count]);
}
}
// NSLog(#"Inhalt Category:%#", categorieContent);
NSArray* tempAr = [[NSArray alloc] initWithArray:[categorieContent allObjects]];
return [NSMutableArray arrayWithArray:tempAr];
}
#end
There has to be a variable conflict with 'catName' in your view controller. I'm not sure why the view controller would be in scope, but I bet if you change your parameter to "inCatName" it will be fine. It's good to use naming conventions like that for this reason.
Related
The problem is that I have error when I try to press magnifying glass (lens) and in index goes to C instead of C. The written code is as follows:
///
// RBook.h
// ObjBook
//
// Created by pan on 24/08/16.
// Copyright © 2016 pan. All rights reserved.
//
#import <Foundation/Foundation.h>
#interface RBook : NSObject
{
}
#property (nonatomic,assign) int ID;
#property (nonatomic,strong) NSString *ISBN;
#property (nonatomic,strong) NSString *Code;
#property (nonatomic,strong) NSString *RBMDate;
#property (nonatomic,strong) NSString *Category;
#property (nonatomic,strong) NSString *FTitle;
#property (nonatomic,strong) NSString *FSubTitle;
#property (nonatomic,strong) NSString *GTitle;
#property (nonatomic,strong) NSString *GSubTitle;
#property (nonatomic,strong) NSString *Authors;
#property (nonatomic,strong) NSString *Publisher;
#property (nonatomic,strong) NSString *Cover;
#property (nonatomic,strong) NSString *CovPhoto;
#property NSInteger section;
#end
//
// RBooks.m
// ObjBook
//
// Created by pan on 24/08/16.
// Copyright © 2016 pan. All rights reserved.
//
#import "RBook.h"
#implementation RBook
#synthesize ID;
#synthesize ISBN;
#synthesize Code;
#synthesize RBMDate;
#synthesize Category;
#synthesize FTitle;
#synthesize FSubTitle;
#synthesize GTitle;
#synthesize GSubTitle;
#synthesize Authors;
#synthesize Publisher;
#synthesize Cover;
#synthesize CovPhoto;
-(NSString *) getName
{
return [NSString stringWithFormat:#"%d %# %# %# %# %# %# %# %# %# %# %# %#",self.ID,self.ISBN,self.Code,self.RBMDate,self.Category,self.FTitle,self.FSubTitle,self.GTitle,self.GSubTitle,self.Authors,self.Publisher,self.Cover,self.CovPhoto];
}
#end
//
// RBooksTableViewController.h
// MyRBooks
//
// Created by pan on 30/08/16.
// Copyright © 2016 pan. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "FMDBDataAccess.h"
#interface RBooksTableViewController : UITableViewController<UISearchBarDelegate , UITableViewDataSource , UITableViewDelegate> {
NSString *tID;
NSString *tFTitle;
NSString *tGTitle;
NSString *tAuthors;
NSString *tPublisher;
NSString *found;
NSString *from;
}
#property (nonatomic,strong) NSMutableArray *books;
#property (nonatomic,strong) NSMutableArray *filteredbooks;
#property (weak, nonatomic) IBOutlet UISearchBar *mysearchBar;
#property (nonatomic, assign) bool isFiltered;
//-(void) populateBooks;
#end
#import "RBooksTableViewController.h"
#import "RBooksTableViewCell.h"
#import "FMDBDataAccess.h"
#import "BooksDetailsViewController.h"
#import "RBook.h"
#implementation RBooksTableViewController
#synthesize books;
#synthesize filteredbooks;
#synthesize mysearchBar;
#synthesize isFiltered;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (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.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
mysearchBar.delegate = (id)self;
tID = #"A/A :";
tFTitle = #"FOREIGN TITLE :";
tGTitle = #"GREEK TITLE :";
tAuthors = #"AUTHORS. :";
tPublisher = #"PUBLISHERS :";
// [self populateBooks];
self.books = [NSMutableArray arrayWithCapacity:1];
NSMutableArray *booksTemp;
// Get the books array from the database
self.books = [[NSMutableArray alloc] init];
FMDBDataAccess *db = [[FMDBDataAccess alloc] init];
booksTemp = [db getBooks];
UILocalizedIndexedCollation *indexedCollation =
[UILocalizedIndexedCollation currentCollation];
// Iterate over the products, populating their section number
for (RBook *therbook in booksTemp) {
NSInteger section = [indexedCollation sectionForObject:therbook
collationStringSelector:#selector(FTitle)];
therbook.section = section;
// NSLog(#" section is %d" , section);
}
// Get the count of the number of sections
NSInteger sectionCount = [[indexedCollation sectionTitles] count];
// NSLog(#" sectionCount is %d" , sectionCount);
// Create an array to hold the sub arrays
NSMutableArray *sectionsArray = [NSMutableArray
arrayWithCapacity:sectionCount];
// Iterate over each section, creating each sub array
for (int i=0; i<=sectionCount; i++) {
NSMutableArray *singleSectionArray = [NSMutableArray
arrayWithCapacity:1];
[sectionsArray addObject:singleSectionArray];
}
// Iterate over the products putting each product into the correct sub-array
for (RBook *therbook in booksTemp) {
[(NSMutableArray *)[sectionsArray objectAtIndex:therbook.section]
addObject:therbook];
}
// Iterate over each section array to sort the items in the section
for (NSMutableArray *singleSectionArray in sectionsArray) {
// Use the UILocalizedIndexedCollation sortedArrayFromArray: method to
// sort each array
NSArray *sortedSection = [indexedCollation
sortedArrayFromArray:singleSectionArray
collationStringSelector:#selector(FTitle)];
[self.books addObject:sortedSection];
// NSLog(#" sortedCollection is %#" , sortedSection);
}
}
- (void)viewDidUnload
{
// [self setSearchBar:nil];
[super viewDidUnload];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if (tableView == self.tableView)
{
return [books count];
}
return 1;
}
NSIndexPath *currentSelection;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
currentSelection = indexPath;
[self showDetailsForIndexPath:indexPath];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
int rowCount;
if(self.isFiltered)
{
rowCount = filteredbooks.count;
} else
rowCount = [[books objectAtIndex:section] count];
return rowCount;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
RBooksTableViewCell *cell = (RBooksTableViewCell *)[self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
cell = [[RBooksTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
RBook* rbook;
if(isFiltered)
rbook = [filteredbooks objectAtIndex:[indexPath row]];
else
// rbook = [books objectAtIndex:[indexPath row]];
rbook = [[books objectAtIndex:[indexPath section]] objectAtIndex:[indexPath row]];
// cell.textLabel.font = [UIFont systemFontOfSize: 17.0]; εχουν μπει στο RBooksTableViewCell.m
// cell.imageView.bounds = CGRectMake(15,17,80,128); εχουν μπει στο RBooksTableViewCell.m
// [[cell textLabel] setText:[NSString stringWithFormat:#"%# %#\r %# %# ", tFirstName,customer.firstName,tLastName,customer.lastName]];
// cell.IDlabel!.text = "\(books.ID_Lbl)"
[[cell textLabel] setText:[NSString stringWithFormat:#"%# %d\r %# %#\r %# %#\r %# %#\r %# %#",tID,rbook.ID,tFTitle,rbook.FTitle ,tGTitle,rbook.GTitle,tAuthors,rbook.Authors,tPublisher,rbook.Publisher]];
[[cell imageView] setImage:[UIImage imageNamed:rbook.CovPhoto]];
return cell;
}
-(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
// create our UIImages
UIImage * defaultBG = [UIImage imageNamed:#"wood1.jpg"];
UIImage * selectedBG = [UIImage imageNamed:#"marble2.jpg"];
// Create UIImageView
UIImageView * defaultBGView = [[UIImageView alloc] initWithImage:defaultBG];
UIImageView * selectedBGView = [[UIImageView alloc] initWithImage:selectedBG];
// set the UIImageView
cell.backgroundColor = [UIColor clearColor];
cell.backgroundView = defaultBGView;
// change the background for the selectedview
cell.selectedBackgroundView = selectedBGView;
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[self.tableView resignFirstResponder];
}
#pragma mark - Table view delegate
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
if(searchText.length==0)
{
isFiltered = FALSE;
}else
{
isFiltered = TRUE;
filteredbooks = [[NSMutableArray alloc] init];
for(RBook* rbook in books)
{
NSRange ftitleRange = [rbook.FTitle rangeOfString:searchText options:NSCaseInsensitiveSearch];
NSRange gtitleRange = [rbook.GTitle rangeOfString:searchText options:NSCaseInsensitiveSearch];
NSRange authorsRange = [rbook.Authors rangeOfString:searchText options:NSCaseInsensitiveSearch];
NSRange publisherRange = [rbook.Publisher rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(ftitleRange.location != NSNotFound || gtitleRange.location != NSNotFound || authorsRange.location != NSNotFound || publisherRange.location != NSNotFound )
{
[filteredbooks addObject:rbook];
}
}
}
found = #"THEY FOUND FOR:";
from = #" / ";
self.title = [NSString stringWithFormat:#"%# %# %lu %# %lu",found , searchText ,(unsigned long)filteredbooks.count ,from , (unsigned long)books.count];
[self. tableView reloadData];
}
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
[self showDetailsForIndexPath:indexPath];
}
//-(void) populateBooks
//{
// self.books = [[NSMutableArray alloc] init];
//
// FMDBDataAccess *db = [[FMDBDataAccess alloc] init];
//
// self.books = [db getBooks];
//}
-(void) showDetailsForIndexPath:(NSIndexPath*)indexPath
{
[self.mysearchBar resignFirstResponder];
BooksDetailsViewController* vc = [self.storyboard instantiateViewControllerWithIdentifier:#"BooksDetailsViewController"];
RBook* rbook;
if(isFiltered)
{
rbook = [filteredbooks objectAtIndex:indexPath.row];
}
else
{
// rbook = [books objectAtIndex:indexPath.row];
rbook = [[books objectAtIndex:[indexPath section]] objectAtIndex:[indexPath row]];
}
vc.rbook = rbook;
[self.navigationController pushViewController:vc animated:true];
}
- (NSString *)tableView:(UITableView *)tableView
titleForHeaderInSection:(NSInteger)section {
// Make sure that the section will contain some data
if ([[books objectAtIndex:section] count] > 0) {
// If it does, get the section title from the
// UILocalizedIndexedCollation object
return [[[UILocalizedIndexedCollation currentCollation] sectionTitles]
objectAtIndex:section];
}
return nil;
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
if (tableView == self.searchDisplayController.searchResultsTableView) {
return nil;
} else {
NSMutableArray *retval = [NSMutableArray arrayWithObject:UITableViewIndexSearch];
[retval addObjectsFromArray:[[UILocalizedIndexedCollation currentCollation] sectionIndexTitles]];
return retval;
}
}
- (NSInteger)tableView:(UITableView *)tableView
sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
return [[UILocalizedIndexedCollation currentCollation]
sectionForSectionIndexTitleAtIndex:index];
//}
}
#end
The problem is somewhere in RBooksTableViewController.m
I have a cocoa app with a window containing an NSTableView. Each row has a few columns, three radio boxes and two buttons. Currently the table has 260 rows and when the window is focused the scrolling in the table view is atrociously slow and jittery. When the window is not focused and I mouse over the table view and scroll it's buttery smooth.
I've tried to solve the slow performance by changing the background drawing and enabling CoreAnimation Layer to no avail.
Why would the scrolling be fast when the window isn't focused but slow when it is?
I'm just baffled as to why the scrolling is so darn slow.
Here's my ProposalTableViewController.h
#import <Cocoa/Cocoa.h>
#import <Foundation/Foundation.h>
#import <QuickLook/QuickLook.h>
#import <Quartz/Quartz.h>
#interface ProposalTableViewController : NSObject<NSTableViewDataSource, NSTableViewDelegate, QLPreviewPanelDelegate, QLPreviewPanelDataSource>{
#public
NSMutableArray *list;
IBOutlet NSTableView *tableView;
IBOutlet NSSearchField *searchText;
IBOutlet NSTextField *countTextField;
}
#property (strong) QLPreviewPanel *previewPanel;
+ (ProposalTableViewController *)getInstance;
- (IBAction)deleteRow:(id)sender;
- (IBAction)exportData:(id)sender;
- (void)loadData;
- (void)countItems;
#end
And my ProposalTableViewController.m
#import "ProposalTableViewController.h"
#import "Proposal.h"
#import "StatusRadioView.h"
#import "DBManager.h"
#import "filePathButtonView.h"
#import <Quartz/Quartz.h>
#import "AppDelegate.h"
#implementation Proposal (QLPreviewItem)
- (NSURL *)previewItemURL
{
return [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#.pdf",self.filePath]];
}
- (NSString *)previewItemTitle
{
return [NSString stringWithFormat:#"Proposal %#",self.proposalNumber];
}
#end
#implementation ProposalTableViewController
static ProposalTableViewController *instance;
+ (ProposalTableViewController *)getInstance{
return instance;
}
//------------------------------------------------------------------------------------------------------------------------------------
// Init
//------------------------------------------------------------------------------------------------------------------------------------
- (id)init{
self = [super init];
if(self){
instance = self;
list = [[NSMutableArray alloc] init];
[self loadData];
for (NSTableColumn *tableColumn in tableView.tableColumns ) {
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:tableColumn.identifier ascending:YES selector:#selector(compare:)];
[tableColumn setSortDescriptorPrototype:sortDescriptor];
}
}
return self;
}
//------------------------------------------------------------------------------------------------------------------------------------
// Load Data from SQLite
//------------------------------------------------------------------------------------------------------------------------------------
- (void)loadData {
list = [[DBManager getProposalTable] select:#""];
NSSortDescriptor* desc = [[NSSortDescriptor alloc] initWithKey:#"proposalNumber" ascending:NO selector:#selector(compare:)];
[list sortUsingDescriptors:[NSArray arrayWithObjects:desc, nil]];
[tableView reloadData];
[self countItems: list];
}
//------------------------------------------------------------------------------------------------------------------------------------
// Number of Rows in Table View
//------------------------------------------------------------------------------------------------------------------------------------
- (NSInteger) numberOfRowsInTableView:(NSTableView *)tableView {
return [list count];
}
-(void)countItems:(NSArray *)list; {
NSString *countText;
int size = [list count];
if (size == 1){
countText = #"item in list";
}else{
countText = #"items in list";
}
NSString *itemCount = [NSString stringWithFormat:#"%d %#", size, countText];
[countTextField setStringValue:itemCount];
}
//------------------------------------------------------------------------------------------------------------------------------------
// Get View for Table Column
//------------------------------------------------------------------------------------------------------------------------------------
- (NSView *)tableView:(NSTableView *)table_view viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
Proposal *p = [list objectAtIndex:row];
NSString *identifier = [tableColumn identifier];
NSString *holdingValue;
NSTableCellView *cell = [table_view makeViewWithIdentifier:identifier owner:self];
if([identifier isEqualToString:#"status"]){
StatusRadioView *radioView = [[StatusRadioView alloc] initWithProposal:p];
return radioView;
}else if ([identifier isEqualToString:#"filePath"]){
filePathButtonView *buttonView = [[filePathButtonView alloc]initWithProposal:p];
return buttonView;
}else if ([identifier isEqualToString:#"clientAccessPoint"]){
holdingValue = [p valueForKey:identifier];
if (!holdingValue){
cell.textField.stringValue = #"N/A";
}else{
cell.textField.stringValue = [p valueForKey:identifier];
}
}else{
cell.textField.stringValue = [p valueForKey:identifier];
}
return cell;
}
//------------------------------------------------------------------------------------------------------------------------------------
// Sort Descriptors did Change
//------------------------------------------------------------------------------------------------------------------------------------
-(void)tableView:(NSTableView *)mtableView sortDescriptorsDidChange:(NSArray *)oldDescriptors {
[list sortUsingDescriptors: [mtableView sortDescriptors]];
[tableView reloadData];
}
//table row height
-(CGFloat)tableView:(NSTableView *)tableView heightOfRow:(NSInteger)row {
return 25;
}
//------------------------------------------------------------------------------------------------------------------------------------
// Search Text did Change
//------------------------------------------------------------------------------------------------------------------------------------
- (void)controlTextDidChange:(NSNotification *)notification {
NSSortDescriptor* desc = [[NSSortDescriptor alloc] initWithKey:#"proposalNumber" ascending:NO selector:#selector(compare:)];
NSTextField *textField = [notification object];
NSString *str = [textField stringValue];
list = [[DBManager getProposalTable] select:str];
[list sortUsingDescriptors:[NSArray arrayWithObjects:desc, nil]];
[tableView reloadData];
[self countItems: list];
}
//------------------------------------------------------------------------------------------------------------------------------------
// Export DATA
//------------------------------------------------------------------------------------------------------------------------------------
- (IBAction)exportData:(id)sender{
NSString *content = #"";
for(Proposal *p in list){
NSString *row = [NSString stringWithFormat:#"%#,%#,%#,%#,%#,%#,%#,%#,%#,%#", p.proposalNumber,p.itemNumber,p.clientName,p.medium,p.support,p.cost,p.dateCreated,p.status,p.dateStatusChanged,p.clientAccessPoint];
row = [row stringByReplacingOccurrencesOfString:#"\n" withString:#""];
row = [NSString stringWithFormat:#"%#\n", row];
content = [content stringByAppendingString:row];
}
//get the documents directory:
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"Baumgartner Fine Art Restoration"];
NSString *fileName = [documentsDirectory stringByAppendingPathComponent:#"proposalBuilderDatabase.csv"];
[[NSFileManager defaultManager] createDirectoryAtPath:documentsDirectory
withIntermediateDirectories:NO
attributes:nil
error:nil];
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
NSAlert *alert = [[NSAlert alloc] init];
[alert setMessageText:#"Export Succeeded"];
[alert addButtonWithTitle:#"Ok"];
[alert runModal];
}
//------------------------------------------------------------------------------------------------------------------------------------
// Delete row from DB and table
//------------------------------------------------------------------------------------------------------------------------------------
- (IBAction)deleteRow:(id)sender{
NSString *row = list[tableView.selectedRow];
NSString *mid = [row valueForKey:#"m_id"];
ProposalTable *deleteRow = [[ProposalTable alloc] init];
[deleteRow deleteWithId: mid];
[self loadData];
[tableView reloadData];
}
//------------------------------------------------------------------------------------------------------------------------------------
// QuickLook
//------------------------------------------------------------------------------------------------------------------------------------
- (NSInteger)numberOfPreviewItemsInPreviewPanel:(QLPreviewPanel *)panel {
return [list count];
}
- (id <QLPreviewItem>)previewPanel:(QLPreviewPanel *)panel previewItemAtIndex:(NSInteger)index {
return list[tableView.selectedRow];
}
- (BOOL)previewPanel:(QLPreviewPanel *)panel handleEvent:(NSEvent *)event {
// redirect all key down events to the table view
if ([event type] == NSKeyDown) {
[tableView keyDown:event];
return YES;
}
return NO;
}
// This delegate method provides the rect on screen from which the panel will zoom.
- (NSRect)previewPanel:(QLPreviewPanel *)panel sourceFrameOnScreenForPreviewItem:(id <QLPreviewItem>)item {
return NSZeroRect;
}
- (BOOL)tableView:(NSTableView *)tableView shouldSelectRow:(NSInteger)rowIndex {
[[QLPreviewPanel sharedPreviewPanel]reloadData];
return YES;
}
#end
Here's my ProposalTableView.h
#import <Cocoa/Cocoa.h>
#interface ProposalTableView : NSTableView
#end
And my ProposalTableView.m
#import "ProposalTableView.h"
#import "AppDelegate.h"
#implementation ProposalTableView
- (void)drawRect:(NSRect)dirtyRect {
[super drawRect:dirtyRect];
self.wantsLayer = YES;
// Drawing code here.
}
- (void)keyDown:(NSEvent *)theEvent
{
NSString *key = [theEvent charactersIgnoringModifiers];
if ([key isEqual:#" "])
{
[[NSApp delegate] togglePreviewPanel:self];
}
else
{
[super keyDown:theEvent];
}
}
#end
There's also code that establishes the SqLite DB connection and interacts with the DB to get the records or delete etc... but that's not really needed here... I also have code that draws the radio buttons and the other buttons but again, I don't think that's necessary unless someone thinks that the drawing is creating the slowdown...?
So it turns out that the drawing of the radio buttons is what is causing the slowdown... back to the drawing board.
I was wondering how to set the progress bar equal to max user input in xcode.
#property (weak, nonatomic) IBOutlet UIProgressView *progressBar;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_inputAmount.keyboardType = UIKeyboardTypeDecimalPad;
self.amount = [NSMutableArray new];
[self.amount addObject:#"Total Amount of Push-Ups:"];
[self.myList setDataSource:self];
_inputAmount = UIProgressViewStyleBar;
}
This is just a snipet of my code, the inputamount = progress bar is what I want to do, but I'm not really sure how to do it. I want the greatest input amount the be equal to the progressviewbar as well. So i would have to compare all the #s that were added to the array. Any ideas? Thanks!
//
// ViewController.m
// Push Up Tracker
//
// Created by Paul Lesny on 10/26/14.
// Copyright (c) 2014 Paul Lesny. All rights reserved.
//
#import "ViewController.h"
#interface ViewController ()
#property (weak, nonatomic) IBOutlet UITextField *inputAmount;
#property (weak, nonatomic) IBOutlet UIButton *addButton;
#property NSMutableArray *amount;
#property (weak, nonatomic) IBOutlet UITableView *myList;
#property (weak, nonatomic) IBOutlet UIProgressView *progressBar;
#end
#implementation ViewController
//#synthesize progressBar, progressValue;
///NSInteger stringToInt(NSString *string) {
//return [string integerValue];
//}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_inputAmount.keyboardType = UIKeyboardTypeDecimalPad;
self.amount = [NSMutableArray new];
[self.myList setDataSource:self];
[self readDataFromFile:#"lalala1"];
if (_amount.count!=0)
{
NSMutableDictionary *max=[_amount objectAtIndex:0];
NSString *m = max[#"max"];
NSLog (#"%#",m);
NSInteger num=[m intValue];
NSLog(#"amount is not empty");
_progressBar.progress = (float) [m intValue]/50;
}
else
{
_progressBar.progress=0;
}
//[self.amount addObject:#"0"];
//[self.myList reloadData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return[self.amount count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString * cellId = #"pancake";//identifier for the cells
// get a cell from the cache
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId];
// if the cell is not cached then
if(cell ==nil)
{
// create a new cell
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
}
NSMutableDictionary *newEntry=_amount[indexPath.row];
[cell.textLabel setText:newEntry[#"pushUpNum"]];
// put the corresponding element of the array as text.
// return the cell.
return cell;
}
-(BOOL) textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
-(void) readDataFromFile:(NSString*)fileName
{
NSData *fileData=[NSData dataWithContentsOfURL:[self urlOfEntries:#"lalala1"]];
if(fileData!=nil)
{
_amount=[NSPropertyListSerialization
propertyListWithData:fileData options:
NSPropertyListMutableContainers format:nil error:nil];
}
else
{
_amount=[NSMutableArray new];
}
}
-(NSURL *) urlOfEntries:(NSString*)name
{
NSURL *docDirectory=[[[NSFileManager defaultManager]
URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask]lastObject];
NSURL* fullPath=[docDirectory URLByAppendingPathComponent:name];
return fullPath;
}
-(void) savePushUpTotal:(NSMutableArray *)myEntries
{
[myEntries writeToURL:[self urlOfEntries:#"lalala1"]atomically:YES];
}
- (IBAction)sender:(id)addButton
{
NSMutableDictionary *newRecord = [[NSMutableDictionary alloc]init];
[newRecord setObject:self.inputAmount.text forKey:#"pushUpNum"];
if (_amount.count==0)
{
[newRecord setObject:#"0" forKey:#"max"];
}
[self.amount addObject:newRecord];
[self savePushUpTotal:_amount];
[self.myList reloadData];
[self.inputAmount resignFirstResponder];
[self savePushUpTotal:_amount];
NSMutableDictionary *max=_amount[0];
NSString *m = max[#"max"];
NSInteger num=[m intValue];
NSMutableDictionary *newDictionary=_amount[_amount.count-1];
NSString *blah = newDictionary[#"pushUpNum"];
NSInteger number=[blah intValue];
NSLog(#"dadala%#",blah);
if (_amount.count!=1)
{
if (number>num)
{
_progressBar.progress= (float)number/50;
NSString *pushUp = max[#"pushUpNum"];
NSMutableDictionary *maxPush = [[NSMutableDictionary alloc]init];
[maxPush setObject:pushUp forKey:#"pushUpNum"];
[maxPush setObject:blah forKey:#"max"];
[_amount removeObjectAtIndex:(NSUInteger)0];
[_amount insertObject:maxPush atIndex:0];
[self savePushUpTotal:_amount];
}
}
else
{
_progressBar.progress = (float)number/50;
}
}
- (IBAction)clear:(UIButton *)sender
{
_progressBar.progress=0;
[_amount removeAllObjects];
[[NSUserDefaults standardUserDefaults] setObject:_amount forKey:0];
[_myList reloadData];
}
#end
I'm trying to save an array of objects with NSCoding when the home button or program is exited, but nothing seems to happen.
What am I doing wrong????
//Fieldbook.h custom object
#interface FieldBook : NSObject <NSCoding>
{
NSString *title;
NSDate *date;
}
#property (nonatomic, retain) NSString *title;
#property (nonatomic, retain) NSDate *date;
-(id) init:(NSString *)aTitle;
- (NSString *) description;
#end
//Fieldbook.m
#import "FieldBook.h"
#implementation FieldBook
#synthesize title, date;
-(id) init:(NSString *)aTitle
{
title = aTitle;
return self;
}
- (NSString *) description
{
NSString *desc = [NSString stringWithFormat:#"%#\n", title];
return desc;
}
- (id)initWithCoder:(NSCoder *)decoder
{
if (self = [super init])
{
self.title = [decoder decodeObjectForKey:#"title"];
self.date = [decoder decodeObjectForKey:#"date"];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder
{
[encoder encodeObject:title forKey:#"time"];
[encoder encodeObject:date forKey:#"date"];
}
#end
//ViewController.h
#interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate>
#property (weak, nonatomic) IBOutlet UITableView *myTableView;
#property (strong, nonatomic) NSMutableArray *fieldBooks;
#property (nonatomic, retain) UITextField *projectName;
- (NSString *)dataFilePath;
#end
//ViewController.m
#import "FieldBook.h"
#import "ViewController.h"
#implementation ViewController
#synthesize myTableView, fieldBooks, projectName;
- (void)viewDidLoad
{
// Do any additional setup after loading the view, typically from a nib.
[super viewDidLoad];
if(fieldBooks == nil)
fieldBooks = [[NSMutableArray alloc]init];
NSMutableArray *tempArray = [NSKeyedUnarchiver unarchiveObjectWithFile:[self dataFilePath]];
[self.fieldBooks addObjectsFromArray:tempArray];
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(applicationWillResignActive:)
name:UIApplicationWillResignActiveNotification
object:app];
[self.myTableView reloadData];
//Set title
self.title = #"FieldBooks";
//Add edit button
self.navigationItem.leftBarButtonItem = self.editButtonItem;
//Add the add button
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
target:self
action:#selector(insertNewObject)];
self.navigationItem.rightBarButtonItem = addButton;
}
- (void)applicationWillResignActive:(NSNotification *)notification
{
[NSKeyedArchiver archiveRootObject:self.fieldBooks toFile:[self dataFilePath]];
}
- (NSString *)dataFilePath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:#"datafile"];
}
- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
[super setEditing:editing animated:animated];
[myTableView setEditing:editing animated:animated];
}
- (void)insertNewObject
{
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Enter name"
message:#""
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"OK", nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
projectName = [alert textFieldAtIndex:0];
[alert show];
}
#pragma mark - UIAlertView delegate method
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
//Only perform if OK button is pressed
if (buttonIndex == 1)
{
FieldBook *fb = [[FieldBook alloc] init:(NSString *)projectName.text];
[fieldBooks addObject:fb];
[myTableView reloadData];
NSLog(#"FieldBook created: %#", fb);
}
}
#pragma mark - UITableView Datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [fieldBooks 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];
}
FieldBook *fbName = [self.fieldBooks objectAtIndex:[indexPath row]];
cell.textLabel.text = fbName.title;
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
//remove from NSMutable array
[fieldBooks removeObjectAtIndex:indexPath.row];
//remove from table view
[myTableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
#end
I have created a .xib file and I'm having a little problem.
I did a video to show you where I'm at with it. The software I am using is Xcode 4.2 and its an iOS application.
Here is a copy of the code in my view .h .m
#import <UIKit/UIKit.h>
#interface myview : UIViewController <UITableViewDelegate, UITableViewDataSource, UIPickerViewDelegate, UIPickerViewDataSource>
#property (strong, nonatomic) IBOutlet UITableView* tableView;
#property (strong, nonatomic) IBOutlet UIPickerView* pickerView;
#property (strong, nonatomic) NSMutableArray* tableData;
#property (strong, nonatomic) NSMutableArray* pickerData;
#end
#import "myview.h"
#implementation myview
#synthesize tableView, pickerView, tableData, pickerData;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (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.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)viewDidUnload
{
[super viewDidUnload];
tableView.delegate = self;
tableView.dataSource = self;
pickerView.delegate = self;
pickerView.dataSource = self;
tableData = [[NSMutableArray alloc] init]; // table starts empty
pickerData = [[NSMutableArray alloc] initWithObjects:#"1", #"2", #"3", #"4", #"5", nil]; // picker starts with values 1, 2, 3, 4, 5
[tableView reloadData];
[pickerView reloadAllComponents]; // Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView {
//The number of sections in UITableView
return 1;
}
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section {
// The number of rows in the UITableView
return [tableData count];
}
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [ [UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
}
// Set the table cell text to the appropriate value in tableDate
cell.textLabel.text = [tableData objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Whatever happens when you select a table view row.
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
// The number of sections in the UIPickerView
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
// The number of rows in the UIPickerView
return [pickerData count];
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
// The data for each row in the UIPickerView
return [pickerData objectAtIndex:row];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
// whatever you want to happen when a row is selected.
// here I am assuming you want to remove from the picker and add to the table on selection
[tableData addObject:[pickerData objectAtIndex:row]];
[pickerData removeObjectAtIndex:row];
[tableView reloadData];
[pickerView reloadAllComponents];
}
#end
I know this is super old and the video is removed so I am not sure what the exact problem is but it is most certainly related to you instantiating everything in our viewDidUnload... You should be doing this in your viewDidLoad most likely.