Is there any easy way to get the number of rows returned by a sqlite statement? I don't want to have to go through the process of doing a COUNT() first. Thanks.
Hi: I want to display a section index in an UITableView with a search bar in the table view header (not section header).
But the index strip is now overlapping the search bar. Is there an elegant solution to avoid this and let the index start below the table header?
I've been working on a game with an engine that updates 20 times per seconds. I've got to point now where I want to start getting some performance figures and tweak the rendering and logic updates. In order to do so I started to add some timing code to my game loop, implemented as follows...
NSDate* startTime = [NSDate date];
// Game update logic here....
// Also timing of smaller internal events
NSDate* endTime = [NSDate date];
[endTime timeIntervalSinceDate:startTime];
I noticed however that when I timed blocks within the outer timing logic that the time they took to execute did not sum up to match the overall time taken.
So I wrote a small unit test to demonstrate the problem in which I time the overall time taken to complete the test and then 10 smaller events, here it is...
- (void)testThatSumOfTimingsMatchesOverallTiming {
NSDate* startOfOverallTime = [NSDate date];
// Variable to hold summation of smaller timing events in the upcoming loop...
float sumOfIndividualTimes = 0.0;
NSTimeInterval times[10] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
for (int i = 0; i < 10; i++) {
NSDate* startOfIndividualTime = [NSDate date];
// Kill some time...
sleep(1);
NSDate* endOfIndividualTime = [NSDate date];
times[i] = [endOfIndividualTime timeIntervalSinceDate:startOfIndividualTime];
sumOfIndividualTimes += times[i];
}
NSDate* endOfOverallTime = [NSDate date];
NSTimeInterval overallTimeTaken = [endOfOverallTime timeIntervalSinceDate:startOfOverallTime];
NSLog(@"Sum of individual times: %fms", sumOfIndividualTimes);
NSLog(@"Overall time: %fms", overallTimeTaken);
STAssertFalse(TRUE, @"");
}
And here's the output...
Sum of individual times: 10.001377ms
Overall time: 10.016834ms
Which illustrates my problem quite clearly. The overall time was 0.000012ms but the smaller events took only 0.000001ms. So what happened to the other 0.000011ms?
Is there anything that looks particularly wrong with my code? Or is there an alternative timing mechanism I should use?
I'm using the following for a LIKE query. Is this technique for LIKE correct?
selectstmtSearch = nil;
if(selectstmtSearch == nil){
const char *sql = "SELECT col1, col2 FROM table1 t1 JOIN table2 t2 ON t1.cityid = t2.cityid where t1.cityname like ?001 order by t1.cityname";
if(sqlite3_prepare_v2(databaseSearch, sql, -1, &selectstmtSearch, NULL) == SQLITE_OK)
{
sqlite3_bind_text(selectstmtSearch, 1, [[NSString stringWithFormat:@"%%%@%%", searchText] UTF8String], -1, SQLITE_TRANSIENT);
}
}
The problem I'm having is after a few uses of this, I get an error 14 on sqlite3_open(), which is unable to open database. If I replace the LIKE with something such as:
SELECT col1, col2
FROM table1 t1
JOIN table2 t2 ON t1.cityid = t2.cityid
where t1.cityname = ?
order by t1.cityname
It works fine. I do open/close the DB before after the above code. Is there a way to troubleshoot exactly why the database can't be opened and what its relationship to my LIKE syntax is?
I'm trying to use the MPMediaPlayback protocol's currentPlaybackRate() to slow down a video. I'm confused though as the class MPMoviePlayerController states that:
You can control most aspects of playback programmatically using the methods and properties of the MPMediaPlayback protocol, to which this class conforms.
Except just above in the header here: http://developer.apple.com/iphone/library/documentation/MediaPlayer/Reference/MPMoviePlayerController_Class/MPMoviePlayerController/MPMoviePlayerController.html it doesn't seem to.
All I want to do is slow down the playback rate for a video.
I know soft shadows are not supported by the UILabel our of the box, on the iPhone. So what would be the best way to implement my own one?
EDIT: Obviously I will subclass the UILabel and draw in the -drawRect:
My question is, how do I get the contents of the label as graphics and draw around them, blur them etc...
I'm pretty sure I've run across this animation at some point, but I can't remember where or how to do it!
I want the equivalent of UIViewAnimationTransitionCurlDown but a full page horizontal curl. Does anybody have code that does this?
Thanks!
Hi,
I would like to bring some color to the texts of my UISegmentedControl. So, I've searched a bit about this topic, but it seems to be not possible out-of-the-box.
But I found this nice blog post (link text), how to build an image out of a custom text and then assign it to the segemented control. Works fine, but the text in these created images do not have this nice little shadow effect as the original ones.
So, does anyone know, how to create such a shadow effect? I guess, Apple does the same (building an image for the text) with the standard segmenented control.
Thanks for your help.
Regards
Matthias
I Have an NSArrayController bound to a NSUserDefaults controller, with setSelectsInsertedObjects set to YES in Interface Builder, but when I click Add, the previously select object gets unselected.
What am I missing?
Hi there! Im using a UIWebView to access a website, when i rotate the phone (landscape) the UIWebView is properly resized and the scrollbar are on the right place (on the right edge...) but when i acess any of input fields to fill the information required and exit it the UIWebView scrollbar jumps to the middle of screen (looks like it get back to 320, the width of the screen on portrait). Some useful info, this program was created using IB, have lots of outlets, im thinking about in do (redo) everything programmatically cause i was not the author of the first version... If anyone have seen this before plz let me know..
Thanks in advance!
I'm writing my first iPhone/Cocoa app. It has two table views inside a navigation view. When you touch a row in the first table view, you are taken to the second table view. I would like the second view to display records from the CoreData entities related to the row you touched in the first view.
I have the CoreData data showing up fine in the first table view. You can touch a row and go to the second table view. I'm able to pass info from the selected object from the first to the second view. But I cannot get the second view to do its own CoreData fetching. For the life of me I cannot get the managedObjectContext object to pass to the second view controller. I don't want to do the lookups in the first view and pass a dictionary because I want to be able to use a search field to refine results in the second view, as well as insert new entries to the CoreData data from there.
Here's the function that transitions from the first to the second view.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic may go here -- for example, create and push another view controller.
NSManagedObject *selectedObject = [[self fetchedResultsController] objectAtIndexPath:indexPath];
SecondViewController *secondViewController = [[SecondViewController alloc] initWithNibName:@"SecondView" bundle:nil];
secondViewController.tName = [[selectedObject valueForKey:@"name"] description];
secondViewController.managedObjectContext = [self managedObjectContext];
[self.navigationController pushViewController:secondViewController animated:YES];
[secondViewController release];
}
And this is the function inside SecondViewController that crashes:
- (void)viewDidLoad {
[super viewDidLoad];
self.title = tName;
NSError *error;
if (![[self fetchedResultsController] performFetch:&error]) { // <-- crashes here
// Handle the error...
}
}
- (NSFetchedResultsController *)fetchedResultsController {
if (fetchedResultsController != nil) {
return fetchedResultsController;
}
/*
Set up the fetched results controller.
*/
// Create the fetch request for the entity.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
// **** crashes on the next line because managedObjectContext == 0x0
NSEntityDescription *entity = [NSEntityDescription entityForName:@"SecondEntity" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
// <snip> ... more code here from Apple template, never gets executed because of the crashing
return fetchedResultsController;
}
Any ideas on what I am doing wrong here?
managedObjectContext is a retained property.
UPDATE: I inserted a NSLog([[managedObjectContext registeredObjects] description]); in viewDidLoad and it appears managedObjectContext is being passed just fine. Still crashing, though.
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '+entityForName: could not locate an NSManagedObjectModel for entity name 'SecondEntity''
Hello i have received this message ever since i started building my first iphone program several months ago. I check if a delegate implements a given method. It works but I get this warning. How can i do it the correct way? Thanks in advance.
I've got a text field value bound to a key path that uses @sum. When the array controller is filtered, the text field updates properly, but extremely slowly, lagging the UI or outright beachballing after every key press (less so as the number of items in arrangedObjects decreases). There is no lag if I don't use @sum; I've narrowed it down to this.
Is there a faster way to do the same thing?
Hi,
I have a UILabel tha contains a URL (ie www.google.com). Is there a way to display the label as URL so the User can tap on the URL for Safari to open it?
Same question I have for a mailto item (ie [email protected]) to open mail with a new email to that address
thanks in advance
Hello,
I am working as an Iphone developer since 5 months but never ever i have used NSfilemanager class. Apple has documentation but still i am not cleared about its use. My question is that can anybody tell me(with example) how and when to use the NSfilemanager class ? Any help will be appreciated. Thanks.
Hi i am doing some research with aurioTouch FFT implementation for one of my audio related project. now i can found the class and the method which calculate the signal strength / power in decibel (dB), but i couldn't find the method from which i can get the frequency. can anyone help me to find which class and its method handling the frequency calculation?
thanks in advance
I have been trying to get this one section of my UI to immediatly up date when the document loads into view. The awakeFromNib fires the pasted code and then starts a timer to repeat every 10 seconds...
I load a default storage location: ~/Movies... which shows up immediately.. yet the network location that is saved in the document that gets pulled from the XML only seems to show up after the second firing of the - (void)updateDiskSpaceDisplay timer.
I have set breakpoints and know that the ivars that contain the values that are being put into the *fileSystemAttributes is the network location right when the awakeFromNib occurs...
Im confused why it magically appears after the second time firing instead of immediately displaying the write values.
- (void)updateDiskSpaceDisplay
{
// Obtain information about the file system used on the selected storage path.
NSError *error = NULL;
NSDictionary *fileSystemAttributes = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[[[self settings] containerSettings] storagePath] error:&error];
if( !fileSystemAttributes ) return;
// Get the byte capacity of the drive.
long long byteCapacity = [[fileSystemAttributes objectForKey:NSFileSystemSize] unsignedLongLongValue];
// Get the number of free bytes.
long long freeBytes = [[fileSystemAttributes objectForKey:NSFileSystemFreeSize] unsignedLongLongValue];
// Update the level indicator, and the text fields to show the current information.
[totalDiskSpaceField setStringValue:[self formattedStringFromByteCount:byteCapacity]];
[totalDiskSpaceField setNeedsDisplay:YES];
[usedDiskSpaceField setStringValue:[self formattedStringFromByteCount:(byteCapacity - freeBytes)]];
[usedDiskSpaceField setNeedsDisplay:YES];
[diskSpaceIndicator setMaxValue:100];
[diskSpaceIndicator setIntValue:(((float) (byteCapacity - freeBytes) / (float) byteCapacity) * 100.0)];
[diskSpaceIndicator display:YES];
}
thoughts?
my awakeFromNib:
- (void)awakeFromNib
{
[documentWindow setAcceptsMouseMovedEvents:YES];
[documentWindow setDelegate:self];
[self updateSettingsDisplay];
[self updateDiskSpaceDisplay];
[self setDiskSpaceUpdateTimer:[NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(updateDiskSpaceDisplay) userInfo:NULL repeats:YES]];
[self setUpClipInfoTabButtons];
[self performSelector:@selector(setupEngineController) withObject:NULL afterDelay:0.1];
}
Hi Guys,
I am getting the data form Parser, In that I am getting a set of urls. Using these urls can I make image url by appending any data values getting from the parser.
http://musicbrainz.org/ws/1/artist/f27ec8db-af05-4f36-916e-3d57f91ecf5e?type=xml&inc=url-rels+artist-rels
using these url i get data and set of urls.They are not providing image url or thumbnail.
So, Is it possible to get or form an image url from parser (http://musicbrainz.org/ws/1/artist/f27ec8db-af05-4f36-916e-3d57f91ecf5e?type=xml&inc=url-rels+artist-rels) and display in the web view.
Please help me from this problem.
Thank You,
Madan Mohan.
I have an app that has a username and password field. I want to validate the input before the the user is allowed to stop editing the field. To do that, I'm using the textFieldShouldEndEditing delegate method. If the input doesn't validate I display a UIAlertView.
This approach works as advertised - the user cannot leave the field if the input doesn't validate.
To have the done button on the keyboard dismiss the keyboard, I call resignFirstResponder on the textfield.
The issue I have is the alert is being called twice. How do I keep the alert from showing twice?
edit for clarification
What is happening is that the alert appears, then another alert appears. I then have to dismiss both windows to fix the input.
Here is the textFieldShouldEndEditing method
-(BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
NSLog(@"function called %@",textField);
if([textField.text length] == 0)
{
return YES;
}
if(textField == userName)
{
if([self userNameValidated:textField.text])
{
NSLog(@"name validated");
NSString *tempDonerName = [[NSString alloc] initWithString:(@"%@",userName.text)];
//[[NSUserDefaults standardUserDefaults] setObject:tempDonerName forKey:@"name"];
[tempDonerName release];
return YES;
} else {
NSLog(@"name did not validate");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Invalid Username",@"Invalid Username title")
message:NSLocalizedString(@"Please make sure there are no apostrophes,spaces in the username, and that the username is less than 12 characters",@"Invalid username message")
delegate:nil
cancelButtonTitle:NSLocalizedString(@"OK",@"OK Text")
otherButtonTitles:nil];
[alert show];
[alert release];
return NO;
}
} else if (textField == userPin) {
if([self userPinValidated:textField.text])
{
NSLog(@"pin validated");
//NSString *tempDonerPin = [[NSString alloc] initWithString:(@"%@",userPin.text)];
//[[NSUserDefaults standardUserDefaults] setObject:tempDonerPin forKey:@"pin"];
//[tempDonerPin release];
return YES;
} else {
NSLog(@"pin did not validate");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Invalid Password",@"Invalid Pin title")
message:NSLocalizedString(@"Please make sure there are no apostrophes in the password",@"Invalid password message")
delegate:nil
cancelButtonTitle:NSLocalizedString(@"OK",@"OK Text")
otherButtonTitles:nil];
[alert show];
[alert release];
return NO;
}
}else {
NSLog(@"code validate - shouldn't get called");
return YES;
}
}
Is there an easy way to do this that works in 10.5?
In 10.6 I can use nsImage CGImageForProposedRect: NULL context: NULL hints: NULL
If I'm not using 1b black and white images (Like Group 4 TIFF), I can use bitmaps, but cgbitmaps seem to not like that setup... Is there a general way of doing this?
I need to do this because I have an IKImageView that seems to only want to add CGImages, but all I've got are NSImages. Currently, I'm using a private setImage:(NSImage*) method that I'd REALLY REALLY rather not be using...
Lets say I have to provide an value as bitmask.
NSUInteger options = kFoo | kBar | kFooBar;
and lets say that bitmask is really huge and may have 100 options. But which options I have, depends on a lot of situations. How could I dynamically compose such a bitmask?
Is this valid?
NSUInteger options;
if (foo) {
options = options | kFoo;
}
if (bar) {
options = options | kBar;
}
if (fooBar) {
options = options | kFooBar;
}
(despite the fact that this would probably crash when doing that | bitmask operator thing to "nothing".
Hi,
I want to know a simple thing, which i couldn't get it is that i want to store 10 values in an integer array dynamically and then i have to check that stored values and compared with the current values whether it is same or not in some other condition. Initially i tried same like C array, int temp[10], but seems to be that is not possible to set and get method, then i tried NSNumber like below,
In AppDelagate file,
NSMutableArray *reqID;
@property (nonatomic,readwrite)
NSMutableArray * reqID;
@synthesize reqID;
........................
........................
........................
In Some other file,
int rd = (1+arc4random() % [arr count]);
[myDelagate.reqID addObject:[NSNumber numberWithUnsignedInteger:rd]];
then i need to check,
for (int i=0; i<10; i++)
{
NSUInteger anInt = [[amyDelagate.reqID objectAtIndex:i] unsignedIntegerValue];
if ( anInt==rd )
{
rd = (1+arc4random() % [arr count]);
break;
}
}
[myDelagate.reqID addObject:[NSNumber numberWithUnsignedInteger:rd]];
But it doesn' work as expected, i.e array value doesn't give proper value. i don't know how to use integer array in Obj-C and handle it to access later etc.
Could someone please explian me?
I have created a UIMenuController and have set it a custom menu item like so:
UIMenuController *menuController = [UIMenuController sharedMenuController];
UIMenuItem *item1 = [[UIMenuItem alloc] initWithTitle:@"Do This" action:@selector(item1)];
[menuController setMenuItems:[NSArray arrayWithObject:item1]];
But I wanted that object to be the only one to appear so I added this code:
- (BOOL)canPerformAction: (SEL)action withSender: (id)sender {
BOOL answer = NO;
if (action == @selector(item1))
answer = YES;
return answer;
}
The problem is it still shows other## Heading ## items, such as "Select", "Select All" and "Paste".
This may have something to do with this being displayed in a UITextView.
But how do I stop if from displaying all other items?