Why are there breaking constraints? - autolayout

I'm trying to learn about visual format language and I'm trying to figure out I get a string of breaking Auto Layout constraints.
/**
* #Name: setUpContainerViews
* #Description: This is will set up the different
* #Parameters: None
* #Returns: void
* #Throws: No Exception
*/
- (void)setUpContainerViews {
tallContainer = [[UIView alloc] init];
self.topContainerView = [[UIView alloc] init];
self.bottomContainerView = [[UIView alloc] init];
self.leftContainerView = [[UIView alloc] init];
self.rightContainerView = [[UIView alloc] init];
// We need to add the subviews here because auto layout needs them to be a part of the view.
[self.view addSubview: tallContainer];
[self.view addSubview: self.rightContainerView];
[tallContainer addSubview: self.topContainerView];
[tallContainer addSubview: self.leftContainerView];
[tallContainer addSubview: self.bottomContainerView];
[self.topContainerView setBackgroundColor: [UIColor blueColor]];
[self.rightContainerView setBackgroundColor: [UIColor orangeColor]];
[self.leftContainerView setBackgroundColor: [UIColor greenColor]];
[self.bottomContainerView setBackgroundColor: [UIColor lightGrayColor]];
}
/**
* #Name: setUpLayoutConstraints
* #Description: This will set up the layout constraints
* #Parameters: none
* #Returns: void
* #Throws: No Exception
*/
- (void)setUpLayoutConstraints {
// Check if all three properties exist
NSMutableArray *constraintArray = [NSMutableArray array];
NSDictionary *views = #{
#"tallContainer":tallContainer,
#"topContainer":self.topContainerView,
#"leftContainer":self.leftContainerView,
#"rightContainer":self.rightContainerView,
#"bottomContainer":self.bottomContainerView
};
// This is for the self.view
[constraintArray addObjectsFromArray: [NSLayoutConstraint constraintsWithVisualFormat: #"H:|-(0)-[tallContainer]-(0)-[rightContainer(50)]-(0)-|" options:0 metrics:nil views: views]];
[constraintArray addObjectsFromArray: [NSLayoutConstraint constraintsWithVisualFormat: #"V:|-(0)-[tallContainer]-(0)-|" options:0 metrics:nil views: views]];
[constraintArray addObjectsFromArray: [NSLayoutConstraint constraintsWithVisualFormat: #"V:|-(0)-[rightContainer]-(0)-|" options:0 metrics:nil views: views]];
// This is for the tall container
[constraintArray addObjectsFromArray: [NSLayoutConstraint constraintsWithVisualFormat: #"V:|-(0)-[topContainer(75)]-(0)-[leftContainer]-(0)-[bottomContainer(75)]-(0)-|" options:0 metrics:nil views: views]];
[constraintArray addObjectsFromArray: [NSLayoutConstraint constraintsWithVisualFormat: #"H:|-(0)-[topContainer]-(0)-|" options:0 metrics:nil views: views]];
[constraintArray addObjectsFromArray: [NSLayoutConstraint constraintsWithVisualFormat: #"H:|-(0)-[leftContainer]-(0)-|" options:0 metrics:nil views: views]];
[constraintArray addObjectsFromArray: [NSLayoutConstraint constraintsWithVisualFormat: #"H:|-(0)-[bottomContainer]-(0)-|" options:0 metrics:nil views: views]];
// This will add the constraints
[self.view addConstraints: [constraintArray copy]];
}
And these are first broken constraints which need to more...
2015-05-16 11:08:34.222 HighSchoolUMS[4776:1420732] Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
"<NSLayoutConstraint:0x7fe898e11760 V:|-(0)-[UIView:0x7fe898e0f210] (Names: '|':UIView:0x7fe898e0f100 )>",
"<NSLayoutConstraint:0x7fe898e117e0 V:[UIView:0x7fe898e0f210(75)]>",
"<NSAutoresizingMaskLayoutConstraint:0x7fe898d2bb80 h=--& v=--& UIView:0x7fe898e0f210.midY ==>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x7fe898e11760 V:|-(0)-[UIView:0x7fe898e0f210] (Names: '|':UIView:0x7fe898e0f100 )>
Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
I don't know why they are breaking it seems like a simple enough thing am I missing something here? (Obviously I am) This app is in landscape orientation is that helps at all.

Related

Playing 2 sounds with AVAudioPlayer without sleep();

I have this 2 sounds playing in a scrollview using AVAudioPlayer.
The problem is that the sleep() is creating lags and I need an alternative to playing two sounds one after the other more easily without the sleep function.
PS: the name of the file is given by the page in the scrollView in which the user is.
if( nextPage!=6 ) {
[scrMain scrollRectToVisible:CGRectMake(0, nextPage*250, scrMain.frame.size.width, scrMain.frame.size.height) animated:YES];
pgCtr.currentPage=nextPage;
NSString *path;
NSError *error;
path = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:#"pas%02i",nextPage+1] ofType:#"m4a"];
if ([[NSFileManager defaultManager] fileExistsAtPath:path])
{
player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error];
player.volume = 0.5f;
[player prepareToPlay];
[player setNumberOfLoops:0];
[player play];
}
sleep(1);
NSString *path2;
NSError *error2;
path2 = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:#"passun%02i",nextPage+1] ofType:#"m4a"];
if ([[NSFileManager defaultManager] fileExistsAtPath:path2])
{
player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path2] error:&error2];
player.volume = 0.5f;
[player prepareToPlay];
[player setNumberOfLoops:0];
[player play];
}
How can I do this?

How to add a method with multiple parameters to the selector of a button

I get this error Terminating app due to uncaught exception 'NSInvalidArgumentException when I try to add a method with multiple parameters to the selector of a button
[viewButton addTarget:self action:#selector(loadDocument: inView:) withObject:cerereIndemnizatie.fisier withObject:self.myWebview forControlEvents:UIControlEventTouchUpInside];
This is the method
-(void)loadDocument:(NSString*)documentName inView:(UIWebView*)webView
{
NSString *path = [[NSBundle mainBundle] pathForResource:documentName ofType:#"pdf"];
NSURL *url = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
}
I don't know why you think you can do this or why would UIButton respond to the addTarget:selector:withObject:withObject:forControlEvents: selector... (Seriously, don't guess, read the documentation...)
You can achieve similar behavior by using associated objects:
UIButton *btn = // create the button
objc_setAssociatedObject(btn, "firstObject", someObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
objc_setAssociatedObject(btn, "secondObject", otherObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
[btn addTarget:self action:#selector(click:) forControlEvents:UIControlEventTouchUpInside];
- (void)click:(UIButton *)sender
{
id first = objc_getAssociatedObject(btn, "firstObject");
id second = objc_setAssociatedObject(btn, "secondObject");
// etc.
}

Loading database at start up slows down the app

i m not sure how to describe this as i m new with all the developing and i m really looking forward to an answer from you guys. I know you can be very busy but please try to HELP me!
Here it goes. I have an app that loads a very large database (although it only has 100 entries it contains HiRes images (100MB) ).
At start up a tableview presents the rows -records (using only 3 attributes from the database). However it seems that the WHOLE database (including the images) is loaded at start up!
IS THERE A WAY TO ONLY LOAD THE 3 attributes (something like "select") when the app starts and then when the user moves to didselectrowatindexpath load the rest of the record?
Because i have NO IDEA where to look or what to do i would appreciate some coding help!
here is the code i m using:
#pragma mark -
#pragma mark App support
- (NSFetchedResultsController *)resetFetchedResultsController:(NSPredicate *)predicate cached:(BOOL)cached
{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Records" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
NSSortDescriptor *partDescriptor = [[NSSortDescriptor alloc] initWithKey:#"displayOrder" ascending:YES];
NSSortDescriptor *nameDescriptor = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects: partDescriptor, nameDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
if (predicate != nil)
[fetchRequest setPredicate:predicate];
NSString *cacheName = nil;
if (cached)
cacheName = #"Root";
NSFetchedResultsController *aFetchedResultsController = [[[NSFetchedResultsController alloc]
initWithFetchRequest:fetchRequest
managedObjectContext:managedObjectContext
sectionNameKeyPath:nil
cacheName:cacheName] autorelease];
aFetchedResultsController.delegate = self;
[fetchRequest release];
[partDescriptor release];
[nameDescriptor release];
[sortDescriptors release];
NSError *error = nil;
if (![aFetchedResultsController performFetch:&error]) {
// Handle error
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
exit(-1); // Fail
}
return aFetchedResultsController;
}
- (void)showRecords:(Records *)records animated:(BOOL)animated {
.
RecordsDetailViewController *detailViewController = [[RecordsDetailViewController alloc] initWithStyle:UITableViewStyleGrouped];
detailViewController.records = records;
[self.navigationController pushViewController:detailViewController animated:animated];
[detailViewController release];
}
#pragma mark -
#pragma mark Table view methods
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
cell.backgroundColor = [UIColor lightGrayColor];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
NSInteger count = [[fetchedResultsController sections] count];
if (count == 0) {
count = 1;
}
return count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSInteger numberOfRows = 0;
if ([[fetchedResultsController sections] count] > 0) {
id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];
numberOfRows = [sectionInfo numberOfObjects];
}
return numberOfRows;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *RecordCellIdentifier = #"RecordCellIdentifier";
RecordTableViewCell *recordCell = (RecordTableViewCell *)[tableView dequeueReusableCellWithIdentifier:RecordCellIdentifier];
if (recordCell == nil) {
recordCell = [[[RecordTableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:RecordCellIdentifier] autorelease];
recordCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
[self configureCell:recordCell atIndexPath:indexPath];
return recordCell;
}
- (void)configureCell:(RecordTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
// Configure the cell
Records *records = (Records *)[fetchedResultsController objectAtIndexPath:indexPath];
cell.records = records;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (self.searchDisplayController.isActive)
[self.tableView reloadData];
Records *records = (Records *)[fetchedResultsController objectAtIndexPath:indexPath];
[self showRecords:records animated:YES];
}
//this is from the RecordTableViewCell.m to show you the attributes i m using:
#pragma mark -
#pragma mark Record set accessor
- (void)setRecord:(Record *)newRecord {
if (newRecord != record) {
[record release];
record = [newRecord retain];
}
imageView.image = [UIImage imageNamed:#"icon.png"];
nameLabel.text = record.name;
overviewLabel.text = record.overview;
partLabel.text = record.part;
}
thanks again...
I would separate the large file from the metadata, because I like to have the freedom to manage these expensive resources seParately. Then I could store them differently, eg filesystem, or http server. This allows me to cache them or send them to remote locAtions proactively to reduce the download times
The rest of the table can then fit in less blocks in the database so less disk access is needed. Many databases do this internally anyway, eg postgresql
You can the just refer to the heavy resource by Id
Ok here it goes. I ve gave up the idea of loading separately the attributes that i need at start up.
What i ve done AND NOW WORKS FLAWLESSLY is to do create RELATIONSHIPS in my model. Images are now loading only when called!
This solution was in my mind but because i had already populated my database it was difficult for me to repeat this step.
However i m glad that i did!
NOW it works as it should!!
Happy Developer!!

Help with UITableView / Navigation Setup with UITabBar Interface

I'm trying to set up a Tab Bar Application as my root controller, and one of the tabs to be a Navigation setup. On my Root View Controller of the Navigation View, I have one child level that is a subclass of the UIViewController called IntervalViewController.
I have this in my Root View Controller (IntervalSetupViewController.m):
#import "IntervalSetupViewController.h"
#import "IntervalViewController.h"
#implementation IntervalSetupViewController
#synthesize controllers; // My Array for the Table View Cells
- (void)viewDidLoad {
self.title = #"Interval Setup";
NSMutableArray *array = [[NSMutableArray alloc] init];
// Interval List Setup
IntervalViewController *newInterval = [[IntervalViewController alloc]
initWithStyle:UITableViewStylePlain];
newInterval.title = #"Interval 1";
[array addObject:newInterval];
[newInterval release];
self.controllers = array;
[array release];
[super viewDidLoad];
}
- (void)viewDidUnload {
self.controllers = nil;
[super viewDidUnload];
}
- (void)dealloc {
[controllers release];
[super dealloc];
}
#pragma mark -
#pragma mark Table Data Source Methods
- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {
return [self.controllers count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *IntervalCell = #"IntervalCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:IntervalCell];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:IntervalCell] autorelease];
}
// Configure the cell
NSUInteger row = [indexPath row];
IntervalViewController *newController = [controllers objectAtIndex:row];
cell.textLabel.text = newController.title;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
#pragma mark Table View Delegate Methods
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger row = [indexPath row];
IntervalViewController *nextController = [self.controllers objectAtIndex:row];
[self.navigationController pushViewController:nextController animated:YES];
}
#end
This is the error screen from the console:
* -[IntervalViewController initWithStyle:]: unrecognized selector sent to instance 0x3b33e60
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[IntervalViewController initWithStyle:]: unrecognized selector sent to instance 0x3b33e60'
I assume that I am passing an invalid argument to my initWithStyle method, but I thought UITableViewStylePlain was a valid parameter. Am I setting this up right? I was following the example in APress Beginning iPhone Development 3 book and trying to modify it a little to what I wanted to do, but I'm new to coding. Thanks!
initWithStyle is used to initialize a UITableViewController not a UIViewController

How to load UIImagePickerController at viewLoad

This seems like a really simple idea... I have a button that says "load a picture". When that button is clicked I want to remove the current view, load a new one, open the image picker, get the selected picture, and display it in the view that I just loaded. I have read several documents that say UIImagePicker does not work in viewDidLoad, and found one thread that suggested using awakeFromNib instead but even that does not work... here is code. Please help.
In MenuViewController
-(IBAction)loadPictureButtonPressed
{
UIView *parent = [self.view superview];
if(self.loadPictureViewController.view.superview == nil)
{
if(self.loadPictureViewController == nil)
{
LoadPictureViewController *picController = [[LoadPictureViewController alloc]
initWithNibName:#"LoadPictureView" bundle: nil];
self.loadPictureViewController = picController;
[picController release];
}
}
[parent addSubview:self.loadPictureViewController.view];
[self.view removeFromSuperview];
}
In LoadPictureViewController
-(void)awakeFromNib
{
if([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypePhotoLibrary])
{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentModalViewController:picker animated:YES];
[picker release];
}
else
{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Error!"
message:#"Device does not support photo library";
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alert show];
[alert release];
}
}
Again I have tried placing this code in both viewDidLoad and awakeFromNib. Please help
I simply set an NSTimer in viewDidLoad with a timer of 0 to select the method where I load it.
[NSTimer scheduledTimerWithTimeInterval:0 target:self selector:#selector(camera) userInfo:nil repeats:NO];
Instead of NSTimer, you probably want to use the following in -viewDidLoad,
[self performSelector:#selector(camera) withObject:nil afterDelay:0];

Resources