Property changes but I can't figure out who's doing it - iphone

I have a UIViewController (called AdjustViewController) that presents another UIViewController (called SourcePickerViewController) with a UIPickerView modally. I generate instances of the AdjustViewController and they in turn make a SourcePickerViewController. I make an NSDictionary and assign it and an integer to the AdjustViewController and it in turn sets the same properties in the SourcePickerController. This way I can reuse the controllers. The NSDictionary get set up in a UITableViewController that has all the AdjustViewControllers in it.
The problem comes when some of the pickers should have 1 component and some should have 2. The integer that I pass along is called numberOfComponents When I make a picker with numberOfComponents = 1 somehow it's changing to = 2 but I can't see how. I have NSLogs all over the place and I can see it happen as soon as the picker delegate method numberOfComponentsInPickerView is called. It's 1 right before and 2 right after.
There's obviously more code, but I think I have all the important parts. Although if that were true, maybe I'd know where the problem is!
Inside MenuViewController.m
- (void)viewDidLoad {
NSLog(#"ChemicalViewController launched");
self.title = #"Adjust Chemicals";
NSMutableArray *array = [[NSMutableArray alloc] init];
// Chlorine Controller
AdjustViewController *chlorineAdjustViewController = [[AdjustViewController alloc] initWithNibName:#"AdjustViewController" bundle:nil];
chlorineAdjustViewController.title = #"FC - Free Chlorine";
chlorineAdjustViewController.numberOfComponents = 2;
NSLog(#"Generating chlorine source dictionary");
NSDictionary *chlorineSourceDictionary = [self generateChlorineDictionary];
chlorineAdjustViewController.dictionaryOfSources = chlorineSourceDictionary;
[chlorineSourceDictionary release];
[array addObject:chlorineAdjustViewController];
[chlorineAdjustViewController release];
// CYA Controller
AdjustViewController *cyaAdjustViewController = [[AdjustViewController alloc] initWithNibName:#"AdjustViewController" bundle:nil];
cyaAdjustViewController.title = #"CYA - Cyanuric Acid";
cyaAdjustViewController.numberOfComponents = 1;
NSLog(#"Generating cya source dictionary");
NSDictionary *cyaSourceDictionary = [self generateCYADictionary];
cyaAdjustViewController.dictionaryOfSources = cyaSourceDictionary;
[cyaSourceDictionary release];
[array addObject:cyaAdjustViewController];
[cyaAdjustViewController release];
Inside AdjustViewController.m
// Present the picker for chlorine selection
- (IBAction)getChemicalSource {
SourcePickerViewController *sourcePickerViewController = [[SourcePickerViewController alloc] init];
sourcePickerViewController.delegate = self;
NSLog(#"getChemicalSource setting numberOfComponents %d", self.numberOfComponents);
sourcePickerViewController.numberOfComponents = self.numberOfComponents;
NSLog(#"getChemicalSource sending numberOfComponents %d", sourcePickerViewController.numberOfComponents);
sourcePickerViewController.dictionaryOfSources = self.dictionaryOfSources;
[self presentModalViewController:sourcePickerViewController animated:YES];
[sourcePickerViewController release];
}
#pragma mark -
#pragma mark Picker View Delegate Methods
// Returns the values from the picker if a source was chosen
- (void)sourcePickerViewController:(SourcePickerViewController *)controller
didSelectSource:(NSString *)source
andConcentration:(NSString *)concentration
andConstant:(float)constant
andIsLiquid:(BOOL)isLiquid {
sourceField.text = [[NSString alloc] initWithFormat:#"%#, %#", source, concentration];
[self updateAdvice];
NSLog(#"Returned source = %#, concentration = %#, sourceConstant = %1.7f, isLiquid = %d", source, concentration, constant, isLiquid);
[self dismissModalViewControllerAnimated:YES];
}
// Returns from the picker without choosing a new source
- (void)sourcePickerViewController:(SourcePickerViewController *)controller
didSelectCancel:(BOOL)didCancel {
[self updateAdvice];
NSLog(#"Returned without selecting source");
[self dismissModalViewControllerAnimated:YES];
}
Inside SourceViewController.m
- (void)viewDidLoad {
NSLog(#"SourcePickerViewController launched");
NSLog(#"viewDidLoad");
NSLog(#"Received numberOfComponents %d", self.numberOfComponents);
self.chemicalSources = dictionaryOfSources;
NSArray *components = [self.chemicalSources allKeys];
NSArray *sorted = [components sortedArrayUsingSelector:#selector(compare:)];
self.sources = sorted; // This array has the chemical sources
if (self.numberOfComponents = 2) {
NSString *selectedSource = [self.sources objectAtIndex:0];
NSArray *chemArray = [self.chemicalSources objectForKey:selectedSource];
NSMutableArray *concentrationArray = [[NSMutableArray alloc] init];
int num = [chemArray count];
for (int i=0; i<num; i++) {
[concentrationArray addObject:[[chemArray objectAtIndex:i] chemConcentration]];
}
self.concentrations = concentrationArray;
}
[super viewDidLoad];
}
#pragma mark -
#pragma mark Picker Data Source Methods
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
NSLog(#"numberOfComponentsInPickerView, self.numberOfComponents = %d", self.numberOfComponents);
return self.numberOfComponents;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
NSLog(#"numberOfRowsInComponent, self.numberOfComponents = %d", self.numberOfComponents);
if (component == kSourceComponent)
return [self.sources count];
return [self.concentrations count];
}
#pragma mark Picker Delegate Methods
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
if (component == kSourceComponent)
return [self.sources objectAtIndex:row];
return [self.concentrations objectAtIndex:row];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
NSLog(#"didSelectRow, self.numberOfComponents = %d", self.numberOfComponents);
if (numberOfComponents = 2) {
if (component == kSourceComponent) {
NSString *selectedSource = [self.sources objectAtIndex:row];
NSArray *chemArray = [self.chemicalSources objectForKey:selectedSource];
NSMutableArray *concentrationArray = [[NSMutableArray alloc] init];
int num = [chemArray count];
for (int i=0; i<num; i++) {
[concentrationArray addObject:[[chemArray objectAtIndex:i] chemConcentration]];
}
self.concentrations = concentrationArray;
[picker selectRow:0 inComponent:kConcentrationComponent animated:YES];
[picker reloadComponent:kConcentrationComponent];
}
}
}
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
if (component == kConcentrationComponent)
return 90;
return 205;
}

I didn't look through all of your code; Instead, I'd recommend writing out the properties for numberOfComponents instead of #synthesize'ing them. Just get rid of your #synthesize, and make:
- (int)numberOfComponents {
return m_numberOfComponents;
}
and
- (void)setNumberOfComponents(int aNumberOfComponents) {
m_numberOfComponents = aNumberOfComponents;
}
Then, set a breakpoint in your setNumberOfComponents function, and you should be able to see whenever it's getting called, so you can see what is going on. I hope that helps!

Related

How to cretae five UIPickerView with tag? And how to give different name to every UIPickerView, in iPhone?

I have 2 UIPickerView right now and I want to add three more later.The code is below:
-(void)viewDidLoad{
Pos_x = 5;
Pos_y = 70;
for (i= 0; i<2; i++) {
myPickerView = [[UIPickerView alloc] init];
myPickerView.frame = CGRectMake(Pos_x,Pos_y,150,300);
myPickerView.tag = i;
myPickerView.delegate = self;
myPickerView.showsSelectionIndicator = YES;
[self.view addSubview:myPickerView];
if (i==0) {
// Init the data array.
Array_1 = [[NSMutableArray alloc] init];
// Add some data for demo purposes.
[Array_1 addObject:#"One"];
[Array_1 addObject:#"Two"];
[Array_1 addObject:#"Three"];
[Array_1 addObject:#"Four"];
[Array_1 addObject:#"Five"];
}
if (i==1) {
Array_2 = [[NSMutableArray alloc] init];
// Add some data for demo purposes.
[Array_2 addObject:#"One1"];
[Array_2 addObject:#"Two1"];
[Array_2 addObject:#"Three1"];
[Array_2 addObject:#"Four1"];
[Array_2 addObject:#"Five1"];
}
Pos_x = Pos_x + 162;
}
}
I have successfully created two UIPickerView with tag. Now the problem is adding data in UIPickerView.
I am doing like this
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
//return [Array_1 objectAtIndex: row]; // If give only this line both UIPickerView show same value.
//How to show both
//return [Array_2 objectAtIndex: row];
// I also tried this code
if(pickerView == myPickerView){
if (i==0){
}
return [Array_1 objectAtIndex: row];
}
if (i==1){
}
return [Array_2 objectAtIndex: row];
}
}
Now my question is that how to show different different data on two UIPickerView? like on pickerview.tag ==0 it will show return [Array_1 objectAtIndex: row];
And pickerview.tag ==1 it will show return [Array_2 objectAtIndex: row];?
Any idea or suggestions would be welcome.
Please check this code:
-(void)viewDidLoad{
myPickerView = [[UIPickerView alloc] init];
myPickerView.frame = CGRectMake(5,70,150,300);
//myPickerView.tag = i;
myPickerView.delegate = self;
myPickerView.showsSelectionIndicator = YES;
[self.view addSubview:myPickerView];
Array_1 = [[NSMutableArray alloc] init];
// Add some data for demo purposes.
[Array_1 addObject:#"One"];
[Array_1 addObject:#"Two"];
[Array_1 addObject:#"Three"];
[Array_1 addObject:#"Four"];
[Array_1 addObject:#"Five"];
[Array_1 addObject:#"Six"];
myPickerView_2nd = [[UIPickerView alloc] init];
myPickerView_2nd.frame = CGRectMake(167,70,150,300);
//myPickerView_2nd.tag = i;
myPickerView_2nd.delegate = self;
myPickerView_2nd.showsSelectionIndicator = YES;
[self.view addSubview:myPickerView_2nd];
Array_2 = [[NSMutableArray alloc] init];
// Add some data for demo purposes.
[Array_2 addObject:#"One1"];
[Array_2 addObject:#"Two1"];
[Array_2 addObject:#"Three1"];
[Array_2 addObject:#"Four1"];
[Array_2 addObject:#"Five1"];
[Array_2 addObject:#"Six1"];
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
if([pickerView isEqual: myPickerView]){
// return the appropriate number of components, for instance
return 1;
}
if([pickerView isEqual: myPickerView_2nd]){
// return the appropriate number of components, for instance
return 1;
}
else
return 0;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent: (NSInteger)component {
if ( pickerView == myPickerView) // this is otherPickerview
{
return [Array_1 count];
}
if ( pickerView == myPickerView_2nd){
return [Array_2 count];
}
else{
NSUInteger numRows = 5;
return numRows;}
}
Hope This will Help You...
You can use an Array or Dictionary to store the content arrays and get them with picker's tag. E. g.
NSArray *contentArrays = [[NSArray alloc] initWithObjects:Array_1, Array_2, nil];
Then get the content array with [contentArrays objectAtIndex:pickerView.tag];
You can do so by setting tags of the pickerview:
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger) {
if(pickerView.tag == 1)
{
// do something with picker one
}
else if(pickerView.tag == 2)
{
// the other picker
}
}
Or else:
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger) {
switch(pickerView.tag){
case 1:
//do something
break;
case 2:
//do other thing
break;
default:
break;
}
}
Hope this helps..
Have a look at this as well: Multiple PickerViews in one View?

Selecting events using Kal calendar

I'm adding a calendar view to my app using Kal Calendar but am having problems implementing a didSelectRowAtIndexPath method on the event list. I would like to push a view controller when the user selects an event for any given day. I've tried putting the method in "KalView.m", "KalViewController.m", and "KalDataSource.m", but none are recognized. Where is the appropriate place to call such a method?
I had similar issue once, Here is how I implemented it.
#import <MTDates/NSDate+MTDates.h>
#import <ObjectiveSugar/ObjectiveSugar.h>
#import <UIImageView+WebCache.h>
#import "EventsViewController.h"
#import "EventDetailsViewController.h"
#import "EventCell.h"
#import "Event.h"
#import "KalViewController.h"
#import "CalendarViewController.h"
#implementation EventsViewController
- (id)initWithEvents:(NSArray *)_events {
self = [super init];
events = _events;
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self listUpdated];
[self addCalendarView];
}
- (void)listUpdated
{
NSMutableArray *allEvents = [NSMutableArray array];
[allEvents addObjectsFromArray:events];
NSArray *sortedArray = [allEvents sortedArrayUsingComparator:^NSComparisonResult(Event *obj1, Event *obj2) {
return [obj1.date compare:obj2.date];
}];
_allEvents = sortedArray;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [_allEvents count];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//custom table cell (EventCell is a view I'm initialising my rows with)
Event *event = _allEvents[indexPath.row];
NSString *reuseIdentifier = [NSString stringWithFormat:#"Cell%#%#", event.venue.identifier, event.identifier];
EventCell *cell = (EventCell*) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
if (!cell) {
cell = [EventCell createDetailedCellWithReuseIdentifier:reuseIdentifier];
cell.nameLabel.text = event.name;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
Event *event = _allEvents[indexPath.row];
EventDetailsViewController *controller = [[EventDetailsViewController alloc] initWithEvent:event];
[self.navigationController pushViewController:controller animated:YES];
}
- (void) addCalendarView{
_calenderView = [[KalViewController alloc] initWithSelectedDate:[NSDate date]];
[[self.view viewWithTag:2] addSubview:_calenderView.view]; /* depends on your requirements*/
_calenderView.view.tag = 200; /* not necessary */
[_calenderView.view setFrame:self.view.bounds];
_calenderView.dataSource = self;
_calenderView.delegate = self;
}
- (void)loadItemsFromDate:(NSDate *)fromDate toDate:(NSDate *)toDate {
//NSLog(#"%#, %#", fromDate, toDate);
// filter and pass the array to the events tableview
[self filterByDateSelected:toDate];
}
-(void)presentingDatesFrom:(NSDate *)fromDate to:(NSDate *)toDate delegate:(id<KalDataSourceCallbacks>)delegate
{
/** when selecting a different month **/
}
- (void)removeAllItems
{
NSLog(#"Items Removed");
// remove all the previous items from the tableview
}
-(void) filterByDateSelected: (NSDate *)selectedDate
{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd"];
NSString *theDate = [dateFormat stringFromDate:selectedDate];
NSDate *_date = [NSDate dateFromString:theDate usingFormat:#"yyyy-MM-dd"];
// filter table by selectedDate
NSArray *_dateFilteredEvents = _allEvents;
_dateFilteredEvents = [_allEvents filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(Event *evaluatedEvent, NSDictionary *bindings) {
if ([evaluatedEvent.date isEqualToDate:_date]) {
return YES;
}
return NO;
}]];
NSLog(#"%#", _dateFilteredEvents);
// uncomment the following line if you want to display list in another controller
//[self showEventsByDate:_dateFilteredEvents];
// or else refresh table after updating the list
_allEvents = _dateFilteredEvents;
[_tableView reloadData];
}
- (void) showEventsByDate:(NSArray*)events
{
if (events.count > 0) {
CalendarViewController *_controller = [[CalendarViewController alloc] initWithEventArray:events];
[self.navigationController pushViewController:_controller animated:YES];
}
}
- (void) removeCalenderView{
[_calenderView.view removeFromSuperview];
}
#end

tableview will not update on phone

If this is a repost, I apologize, but I have been scouring the net and cant seem to find anything that works. I have a list of workouts that I display in a tableview that are gathered in plists in the bundle. There is a also a separate tab that I have that allows a user to build their own workouts and save them in the documents folder plist file. Once they are saved, they are added to the table view. In the simulator, everyuhting works fine. But on the actual device, it is not updated unless I close the program for an extended period of time, reload the program from xcode, or turn the phone off. I have tried adding [[self tableview] reload] to "viewDidLoad", "viewWillappear", and "viewDidAppear" and none of them work. Once again, the file is saved, the updating does work in the simulator, and it doesn't update in the phone right away. Any suggestions? Thanks.
Edit: i know it is a long piece of code, but should be straight forward (hopefully lol)
#import "BIDWODList.h"
#import "BIDWODDetails.h"
#define kFileName #"SavedDFWorkouts.plist"
#interface BIDWODList ()
#end
#implementation BIDWODList
#synthesize names;
#synthesize savedNames;
#synthesize keys;
#synthesize details;
#synthesize wodType;
#synthesize benchmarkGirls;
#synthesize theNewGirls;
#synthesize heroes;
#synthesize savedDFGWorkouts;
#synthesize chosenWOD;
#synthesize chosenDetails;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSMutableArray *buildBenchmarkGirls = [[NSMutableArray alloc] init];
NSMutableArray *buildTheNewGirls = [[NSMutableArray alloc] init];
NSMutableArray *buildHeroes = [[NSMutableArray alloc] init];
NSBundle *bundle = [NSBundle mainBundle];
NSURL *plistURL = [bundle URLForResource:#"CrossfitWOD" withExtension:#"plist"];
//put the contents of the plist into a NSDictionary, and then into names instance variable
NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfURL:plistURL];
self.names = dictionary;
//take all the keys in the dictionary and make an array out of those key names
self.keys = [self.names allKeys];
for (NSString *nameCheck in keys){
self.details = [names valueForKey:nameCheck];
if ([[self.details valueForKey:#"Type"] isEqualToString:#"The Benchmark Girls"]) {
[buildBenchmarkGirls addObject:nameCheck];
}else if ([[self.details valueForKey:#"Type"] isEqualToString:#"The New Girls"]) {
[buildTheNewGirls addObject:nameCheck];
}else {
[buildHeroes addObject:nameCheck];
}
}
NSString *filePath = [self dataFilePath];
NSMutableDictionary *savedWorkout = [[NSMutableDictionary alloc]initWithContentsOfFile:filePath];
self.savedNames = savedWorkout;
self.savedDFGWorkouts = [[savedWorkout allKeys] sortedArrayUsingSelector:#selector(compare:)];
self.benchmarkGirls = [buildBenchmarkGirls sortedArrayUsingSelector:#selector(compare:)];
self.theNewGirls = [buildTheNewGirls sortedArrayUsingSelector:#selector(compare:)];
self.heroes = [buildHeroes sortedArrayUsingSelector:#selector(compare:)];
//[[self tableView] reloadData]; //reloads the data in case a DFG workout was saved
}
- (void)viewDidUnload
{
[super viewDidUnload];
self.names = nil;
self.keys = nil;
self.benchmarkGirls = nil;
self.theNewGirls = nil;;
self.heroes = nil;
self.details = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (NSString *)dataFilePath {
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:kFileName];
}
-(void)viewDidAppear:(BOOL)animated{
[[self tableView] reloadData];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 4;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
if (section == 0) {
return [benchmarkGirls count];
}else if (section == 1){
return [theNewGirls count];
}else if (section == 2){
return [heroes count];
}else{
return [savedDFGWorkouts count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger section = [indexPath section];
NSUInteger row = [indexPath row];
static NSString *SectionsTableIdentifier = #"SectionsTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SectionsTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SectionsTableIdentifier];
}
if (section == 0) {
cell.textLabel.text = [benchmarkGirls objectAtIndex:row];
}else if (section == 1) {
cell.textLabel.text = [theNewGirls objectAtIndex:row];
}else if (section == 2) {
cell.textLabel.text = [heroes objectAtIndex:row];
}else{
cell.textLabel.text = [savedDFGWorkouts objectAtIndex:row];
}
return cell;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if (section == 0) {
return #" The Benchmark Girls";
}else if (section == 1){
return #"The New Girls";
}else if (section ==2){
return #"The Heroes";
}else{
return #"Saved DFG Workouts";
}
}
#pragma mark - Table view delegate
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
BIDWODDetails *destination = segue.destinationViewController;
NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
NSUInteger section = [indexPath section];
NSUInteger row = [indexPath row];
if (section == 0) {
self.chosenWOD = [self.benchmarkGirls objectAtIndex:row];
self.chosenDetails = [names objectForKey:chosenWOD];
}else if (section == 1) {
self.chosenWOD = [self.theNewGirls objectAtIndex:row];
self.chosenDetails = [names objectForKey:chosenWOD];
}else if (section ==2) {
self.chosenWOD = [self.heroes objectAtIndex:row];
self.chosenDetails = [names objectForKey:chosenWOD];
}else {
self.chosenWOD = [self.savedDFGWorkouts objectAtIndex:row];
self.chosenDetails = [savedNames objectForKey:chosenWOD];
}//end if
//self.chosenDetails = [names objectForKey:chosenWOD];
//[destination setValue:chosenWOD forKey:#"chosenWOD"];
//[destination setValue:chosenDetails forKey:#"chosenDetails"];
destination.chosenWOD = self.chosenWOD;
destination.chosenDetails = self.chosenDetails;
}
#end
Different behaviour between the simulator and the device is often related to incorrect case being used in filenames - the simulator isn't case sensitive, and the device is. Check that you have the correct case used everywhere you reference the plist file.
Alternatively, on the simulator you are able to write directly to the application bundle, but on the device this is not possible and you can only write to certain directories in your application's sandbox, typically the documents directory. You would normally copy a plist to the documents directory on first run, and use that file thereafter.
If I understand right your code you load plist file only in viewDidLoad, but most likely this function called only when you first time load your view. To make it work you should load plist
in viewDidAppear. Something like this:
- (void)viewDidAppear {
NSBundle *bundle = [NSBundle mainBundle];
NSURL *plistURL = [bundle URLForResource:#"CrossfitWOD" withExtension:#"plist"];
//put the contents of the plist into a NSDictionary, and then into names instance variable
NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfURL:plistURL];
self.names = dictionary;
//take all the keys in the dictionary and make an array out of those key names
self.keys = [self.names allKeys];
for (NSString *nameCheck in keys){
self.details = [names valueForKey:nameCheck];
if ([[self.details valueForKey:#"Type"] isEqualToString:#"The Benchmark Girls"]) {
[buildBenchmarkGirls addObject:nameCheck];
}else if ([[self.details valueForKey:#"Type"] isEqualToString:#"The New Girls"]) {
[buildTheNewGirls addObject:nameCheck];
}else {
[buildHeroes addObject:nameCheck];
}
}
NSString *filePath = [self dataFilePath];
NSMutableDictionary *savedWorkout = [[NSMutableDictionary alloc]initWithContentsOfFile:filePath];
self.savedNames = savedWorkout;
self.savedDFGWorkouts = [[savedWorkout allKeys] sortedArrayUsingSelector:#selector(compare:)];
[self.tableView reloadData];
}
If it works in the Simulator and does not on the phone, almost for sure the problem is a timing issue. Saving files on a real phone takes much longer than on the simulator.
You should do the following:
when you save a file, log it, and log the return code from the save. If the way you save does not provide a return code, use NSFileManager to verify the file is in fact where it should be and even the size of it. This takes time to do but you should do it.
when your table is asking for the number of this and that, log it, and lot what is returned. You may find that that this comes before the files are saved.
It takes time and effort, but if you start logging all relevant things, you can find it. I just spend 6 hours today tracking down a race condition I had thought could never happen, and it was only after looking at a huge trail of messages that I was able to see the problem.
Almost for sure you will see that either file is not saved, its not where you thought it was, or that the phone timing means some events happen later than they do in the Simulator.

My label can't get value from pickerview

My numberOfComponentsInPickerView :
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 3;
}
My numberOfRowsInComponent :
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
if (component == 0)
return 100;
if (component == 1)
return 100;
if (component == 2)
return 100;
return 0;
}
My titleForRow like this:
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
if (component == 0)
return [NSString stringWithFormat:#"%d", row];
if (component == 1)
return [NSString stringWithFormat:#"%d", row];
if (component == 2)
return [NSString stringWithFormat:#"%d", row];
return 0;
}
my didSelectRow like this
after edited like Paras Joshi's said :
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
int year = [picker selectedRowInComponent:0];
int month = [picker selectedRowInComponent:1];
int day = [picker selectedRowInComponent:2];
if(viewPicker.tag == 1)
labelDate1.text = [year stringByAppendingFormat:#" : %d : %d", month, day];
else
labelDate2.text = [year stringByAppendingFormat:#" : %d : %d", month, day];
}
it still gives me error " bad receiver type 'int' " and i still don't get it how to fix it. how my label get data from titleForRow?
both input for year month and day all are number only (from 0 to 99) so that i wrote -> return [NSString stringWithFormat:#"%d", row];
i dont put data for my pickerview at - (void)viewDidLoad because i want my labelDate1 or labelDate2 got data from pickerview. is there any possible my label get data from pickerview like i wrote above? or must i write my data at - (void)viewDidLoad ?
for any help, thank you for watching my question.
In your program you are appending string to an integer that is the issue.
This code makes the issue. Because year is an integer.
labelDate1.text = [year stringByAppendingFormat:#" : %d : %d", month, day];
Please check with this code.
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
int year = [picker selectedRowInComponent:0];
int month = [picker selectedRowInComponent:1];
int day = [picker selectedRowInComponent:2];
NSString *date = #"";
if(viewPicker.tag == 1)
labelDate1.text = [date stringByAppendingFormat:#" %d : %d : %d",year, month, day];
else
labelDate2.text = [date stringByAppendingFormat:#"%d : %d : %d", year, month, day];
}
Did you set the UIPickerView's delegate?I mean, did your pickerView:didSelectRow:inComponent get called?
Hello #Piyo Piyo your
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
method is totally wrong, you are assigning NSInteger to NSString. Thats why you are getting en error. You should use NSArray for putting data in picker view row and picking data from here. Here i'm going to make a small sample code.
This is your viewController.h file...
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController<UIPickerViewDelegate, UIPickerViewDataSource>
{
UIPickerView *myPickerView;
NSMutableArray *arrayYear;
NSMutableArray *arrayMonth;
NSMutableArray *arrayDay;
UILabel *lblDay;
UILabel *lblMonth;
UILabel *lblYear;
}
#end
there are three array which will contain the data for day, month and year respectively and three UILabel for showing the data. and obviously one pickerview.
Now come to on your viewController.m part.
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// UIPickerView declaration by coding
myPickerView = [[UIPickerView alloc]initWithFrame:CGRectMake(0.0, 0.0, 320.0, 216.0)];
myPickerView.delegate = self;
myPickerView.showsSelectionIndicator = YES;
[self.view addSubview:myPickerView];
// add some day number to day array
arrayDay = [[NSMutableArray alloc]init];
for(int i=1;i<6;i++)
{
NSString *string = [NSString stringWithFormat:#"%d",i];
[arrayDay addObject:string];
}
// add some month string to month array
arrayMonth = [[NSMutableArray alloc]init];
[arrayMonth addObject:#"June"];
[arrayMonth addObject:#"July"];
[arrayMonth addObject:#"August"];
[arrayMonth addObject:#"September"];
[arrayMonth addObject:#"October"];
// add some year number to year array
arrayYear = [[NSMutableArray alloc]init];
for(int i=2006;i<2011;i++)
{
NSString *string = [NSString stringWithFormat:#"%d",i];
[arrayYear addObject:string];
}
//set initially text to day label
lblDay = [[UILabel alloc]initWithFrame:CGRectMake(10.0, 250.0, 90.0, 50.0)];
[lblDay setText:[arrayDay objectAtIndex:0]];
[self.view addSubview:lblDay];
//set initially text to month label
lblMonth = [[UILabel alloc]initWithFrame:CGRectMake(110.0, 250.0, 90.0, 50.0)];
[lblMonth setText:[arrayMonth objectAtIndex:0]];
[self.view addSubview:lblMonth];
//set initially text to year label
lblYear = [[UILabel alloc]initWithFrame:CGRectMake(210.0, 250.0, 90.0, 50.0)];
[lblYear setText:[arrayYear objectAtIndex:0]];
[self.view addSubview:lblYear];
//set initially selection to each component of UIPickerView
[myPickerView selectRow:1 inComponent:0 animated:NO];
[myPickerView selectRow:1 inComponent:1 animated:NO];
[myPickerView selectRow:1 inComponent:2 animated:NO];
}
//here you are returning the number of component, which are 3 in this case
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;
{
return 3;
}
//this is your didSelectRow method and here you are assigning a new text to
//label accordingly to if condition
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if(component == 0)
{
lblDay.text = [arrayDay objectAtIndex:row];
}
if(component == 1)
{
lblMonth.text = [arrayMonth objectAtIndex:row];
}
if(component == 2)
{
lblYear.text = [arrayYear objectAtIndex:row];
}
}
//this is your numberOf row in component in this case each component have 5
//rows thats why i wrote only return 5; here you can put if condition here for
//returning different rows for each component
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;
{
return 5;
}
// and this is showing title on rows
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component;
{
if (component == 0)
return [arrayDay objectAtIndex:row];
else if (component == 1)
return [arrayMonth objectAtIndex:row];
else if (component == 2)
return [arrayYear objectAtIndex:row];
else
return 0;
}
I hope this tutorial will help you. Thank you!

Array out of bounds and slow slow app

So below is my code for my controller, which I have four of one for each tab on the tab bar. I have two issues.
I am getting an array out bounds but I can't chase it down. Am I missing something here?
Second when my app starts up it take 5 - 8 seconds before it loads the first view of the tab bar. Once it loads and I click another tab, the tab doesn't turn blue and the app sits there for 3 seconds then finally switches. I am a noob and am struggling here. I think this issue might be fixed by fetching the data in another thread or something? I am sure this controller is full of bugs.
import "AllMackTableViewController.h"
import "PostDetailViewController.h"
import "MackdabMobileAppDelegate.h"
import <QuartzCore/QuartzCore.h>
import "Post.h"
define FONT_SIZE 14.0f
define CELL_CONTENT_WIDTH 254.0f
define CELL_CONTENT_MARGIN 5.0f
#implementation AllMackTableViewController
#synthesize jsonArray;
#synthesize localJsonArray;
#synthesize postDetailViewController;
#synthesize allPostsTableView;
#synthesize fetchedResultsController, managedObjectContext;
#synthesize minuteTimer;
#synthesize regionsTimer;
pragma mark
pragma mark View lifecycle
(void)viewDidLoad {
[super viewDidLoad];
self.title = NSLocalizedString(#"Feed", #"You're Matching Posts");
UIBarButtonItem *refreshButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
target:self
action:#selector(refresh)];
self.navigationItem.rightBarButtonItem = refreshButton;
allPostsTableView.delegate = self;
[refreshButton release];
[self refresh];
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
(void)scrollViewDidScroll:(UIScrollView *) scrollView;
{
CGFloat scrollHeight = scrollView.contentSize.height;
CGPoint p = scrollView.contentOffset;
//NSLog(#"x = %f, y = %f", p.x, p.y);
}
(void)viewWillAppear:(BOOL)animated {
/*
Set up two timers, one that fires every minute, the other every fifteen minutes.
1/ The time displayed for each time zone must be updated every minute on the minute.
2/ Time zone data is cached. Some time zones are based on 15 minute differences from GMT, so update the cache every 15 minutes, on the "quarter".
*/
NSTimer *timer;
NSDate *date = [NSDate date];
/*
Set up a timer to update the table view every minute on the minute so that it shows the current time.
*/
NSDate *oneMinuteFromNow = [date dateByAddingTimeInterval:60];
NSCalendarUnit unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit;
NSDateComponents *timerDateComponents = [calendar components:unitFlags fromDate:oneMinuteFromNow];
// Add 1 second to make sure the minute update has passed when the timer fires.
[timerDateComponents setSecond:1];
NSDate *minuteTimerDate = [calendar dateFromComponents:timerDateComponents];
timer = [[NSTimer alloc] initWithFireDate:minuteTimerDate interval:60 target:self selector:#selector(updateTime:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
self.minuteTimer = timer;
[timer release];
}
pragma mark
pragma mark Table view data source
(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
// return [self.localJsonArray count];
NSLog(#"Setting numberOfRowsInSection to %i",[self.localJsonArray count]);
if ( [jsonArray count] < 9 ) {
return [self.localJsonArray count];
NSLog(#"Setting numberOfRowsInSection to %i inside of non add one.",[self.localJsonArray count]);
} else {
return [self.localJsonArray count] + 1;
}
}
(void)updateTime:(NSTimer *)timer {
/*
To display the current time, redisplay the time labels.
Don't reload the table view's data as this is unnecessarily expensive it recalculates the number of cells and the height of each item to determine the total height of the view etc. The external dimensions of the cells haven't changed, just their contents.
*/
NSArray *visibleCells = self.tableView.visibleCells;
for (PostTableCustomCellController *cell in visibleCells) {
[cell redisplay];
}
[self updateRegions];
}
(NSString *)dateDiff:(NSString *)origDate {
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setFormatterBehavior:NSDateFormatterBehavior10_4];
[df setDateFormat:#"EEE, dd MMM yy HH:mm:ss VVVV"];
NSDate *convertedDate = [df dateFromString:origDate];
[df release];
NSDate *todayDate = [NSDate date];
double ti = [convertedDate timeIntervalSinceDate:todayDate];
ti = ti * 1;
if(ti < 1) {
return #"never";
} else if (ti < 60) {
return #"less than a minute ago";
} else if (ti < 3600) {
int diff = round(ti / 60);
return [NSString stringWithFormat:#"%d minutes ago", diff];
} else if (ti < 86400) {
int diff = round(ti / 60 / 60);
return[NSString stringWithFormat:#"%d hours ago", diff];
} else if (ti < 2629743) {
int diff = round(ti / 60 / 60 / 24);
return[NSString stringWithFormat:#"%d days ago", diff];
} else {
return #"never";
}
}
(void)updateRegions {
/*
The following sets the date for the regions, hence also for the time zone wrappers. This has the sideeffect of "faulting" the time zone wrappers (see TimeZoneWrapper's setDate: method), so can be used to relieve memory pressure.
*/
NSDate *date = [NSDate date];
for (Post *post in localJsonArray) {
post.timeRemaining = [self dateDiff:post.deadline];
}
}
// Customize the appearance of table view cells.
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UILabel *distance;
UIImage *image = [UIImage imageNamed:#"imageA.png"];
static NSString *CellIdentifier = #"customCell"; // This is identifier given in IB jason set this.
PostTableCustomCellController *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (indexPath.row != [localJsonArray count] ) {
if (cell == nil) {
NSLog(#"Cell created");
NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:#"PostTableCustomCellController" owner:nil options:nil];
for(id currentObject in nibObjects)
{
if([currentObject isKindOfClass:[PostTableCustomCellController class]])
{
cell = (PostTableCustomCellController *)currentObject;
}
}
}
Post *post = [localJsonArray objectAtIndex:indexPath.row];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy"];
//Optionally for time zone converstions
//[formatter setTimeZone:[NSTimeZone timeZoneWithName:#"..."]];
NSString *stringFromDate = [formatter stringFromDate:post.deadline];
cell.authorName.text = post.author;
cell.deadline.text = stringFromDate;
cell.budget.text = post.budget;
cell.description.text = post.description;
[[cell avatar] setImage:[UIImage imageNamed:#"butterfly.jpeg"]];
[stringFromDate release];
NSLog([NSString stringWithFormat:#"%#", post.distance]);
if([#"" isEqualToString: post.distance] || nil == post.distance) {
cell.distance.text = #"1 mi.";
}else{
cell.distance.text = #"25 mi.";
}
Post *myPost = [localJsonArray objectAtIndex:[indexPath row]];
// Might can remove these
UILabel *locationLabel = (UILabel *) [cell distance];
UITextView *postTextView = (UITextView *) [cell description];
//CGSize maximumLabelSize = CGSizeMake(254,88.0f);
NSString *text;
CGSize constraint;
CGSize size;
CGFloat height;
CGFloat realHeight;
CGSize expectedLabelSize;
text = myPost.description;
constraint = CGSizeMake(CELL_CONTENT_WIDTH (CELL_CONTENT_MARGIN * 2), 88.0f);
size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
height = MAX(size.height, 35.0f);
realHeight = height + 36.0f (10);
expectedLabelSize = [text sizeWithFont:[UIFont boldSystemFontOfSize:18.0f] constrainedToSize:CGSizeMake(252.0f, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap];
CGRect newFrame = postTextView.frame;
newFrame.size.height = expectedLabelSize.height;
newFrame.size.width = 252;
postTextView.frame = newFrame;
[[cell description] sizeToFit];
[[cell viewForBackground] sizeToFit];
[cell setNeedsDisplay];
}// Ok, all done for filling the normal cells, next we probaply reach the +1 index, which doesn’t contain anything yet
if ( [jsonArray count] == 9 ) { // Only call this if the array count is 25
if(indexPath.row == [localJsonArray count] ) { // Here we check if we reached the end of the index, so the +1 row
if (cell == nil) {
cell = [[[PostTableCustomCellController alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
// Reset previous content of the cell, I have these defined in a UITableCell subclass, change them where needed
cell.authorName.text = nil;
cell.deadline.text = nil;
cell.budget.text = nil;
cell.description.text = nil;
// Here we create the ‘Load more’ cell
UILabel *loadMore =[[UILabel alloc]initWithFrame: CGRectMake(20,0,362,100)];
loadMore.textColor = [UIColor blackColor];
loadMore.highlightedTextColor = [UIColor darkGrayColor];
loadMore.backgroundColor = [UIColor clearColor];
loadMore.font=[UIFont fontWithName:#"Verdana" size:20];
loadMore.textAlignment=UITextAlignmentCenter;
loadMore.font=[UIFont boldSystemFontOfSize:20];
loadMore.text=#"Load More..";
[cell addSubview:loadMore];
}
}
return cell;
}
(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
if (indexPath.row != [localJsonArray count] ) {
Post *myPost = [localJsonArray objectAtIndex:[indexPath row]];
NSString *text = myPost.description;
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH (CELL_CONTENT_MARGIN * 2), 88.0f);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
CGFloat height = MAX(size.height, 35.0f);
return height + (CELL_CONTENT_MARGIN * 2) + 28.0f;
}else{
return 100.0f;
}
}
(IBAction)nextTwentyFivePlease:(NSString *)thePostID{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
self.jsonArray = [Post findNextTwentyFiveRemote:thePostID];
if (self.localJsonArray == nil) {
self.localJsonArray = [[NSMutableArray alloc]init]; // init the local array if it’s empty
}
[self.localJsonArray addObjectsFromArray:self.jsonArray];
[self.tableView reloadData];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
(IBAction)refresh {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
self.jsonArray = [Post findAllRemote];
if (self.localJsonArray == nil) {
self.localJsonArray = [[NSMutableArray alloc]init]; // init the local array if it’s empty
}
[self.localJsonArray addObjectsFromArray:self.jsonArray];
//self.localJsonArray = [Post findAllRemote];
[self.tableView reloadData];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
pragma mark
pragma mark Table view delegate
(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if ( [jsonArray count] == 9 ) { // only check for the load more function if we have 25 results in the dynamic array
if (indexPath.row == [localJsonArray count] ) { // See if we reached the +1 in the results
Post *tempPost = [jsonArray objectAtIndex:indexPath.row];
NSLog('What is at tempPost');
[self nextTwentyFivePlease:tempPost.postID]; // function to load more results
}
} else {
NSInteger row = [indexPath row];
if (self.postDetailViewController == nil) {
PostDetailViewController *aPostDetail = [[PostDetailViewController alloc] initWithNibName:#"PostDetailView" bundle:nil];
self.postDetailViewController = aPostDetail;
postDetailViewController.post = [localJsonArray objectAtIndex:row];
[aPostDetail release];
}
postDetailViewController.title = [NSString stringWithFormat:#"Details"];
MackdabMobileAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
[delegate.allMacksNavController pushViewController:postDetailViewController animated:YES];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
}
pragma mark
pragma mark Timer set accessor methods
(void)setMinuteTimer:(NSTimer *)newTimer {
if (minuteTimer != newTimer) {
[minuteTimer invalidate];
minuteTimer = newTimer;
}
}
(void)setRegionsTimer:(NSTimer *)newTimer {
if (regionsTimer != newTimer) {
[regionsTimer invalidate];
regionsTimer = newTimer;
}
}
pragma mark
pragma mark Memory management
(void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Relinquish ownership any cached data, images, etc that aren't in use.
}
(void)viewDidUnload {
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
}
(void)dealloc {
[allPostsTableView release];
[postDetailViewController release];
[localJsonArray release]; // may need to remove this
[super dealloc];
}
#end
In your refresh method which is called in viewDidLoad, it appears that it is doing a bunch of network access to download some information. That would explain why it is taking so long to show your initial tab.
You'll want to do that network access in a background thread so that your UI doesn't block. Then once you've gotten the results back you can update your UI from the main thread. Something like:
- (IBAction) refresh {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[self performSelectorInBackground:#selector(refreshInBackground) withObject:nil];
}
- (void) refreshInBackground {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
self.jsonArray = [Post findAllRemote];
if (self.localJsonArray == nil) {
self.localJsonArray = [[NSMutableArray alloc]init]; // init the local array if it’s empty
}
[self.localJsonArray addObjectsFromArray:self.jsonArray];
[self performSelectorOnMainThread:#selector(refreshComplete) withObject:nil waitUntilDone:NO];
}
- (void) refreshComplete {
[self.tableView reloadData];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
EDIT: As Rob noted in the comment below, you'll want to add some kind of flag (or semaphore) to avoid firing off multiple -refresh calls at the same time. Threading and race conditions are always a tricky bit, but my goal above was just to get you moving in the right direction so that you can use background threads for your network calls.