How to improve the following code in Objective-C? - ios4

I have the following code that displays the alerts depending on the result: How can I improve the following code:
-(IBAction)saveSettings:(id)sender
{
UIAlertView *alert = nil;
username = self.usernameTextField.text;
token = self.passwordTextField.text;
// validate the username and token
if(![self isValid])
{
// show alert that it is not valid
alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Invalid User Name or Password" delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok", nil];
[alert show];
return;
}
BOOL isSynched = [self syncSettings];
if(!isSynched)
{
alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Error Syncing Settings" delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok", nil];
[alert show];
}
else
{
alert = [[UIAlertView alloc] initWithTitle:#"" message:#"Settings has been Synced Syncing" delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok", nil];
[alert show];
}
}
I think I am instantiating the alert too many times and looks kind of repetitive!

username = self.usernameTextField.text;
token = self.passwordTextField.text;
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#""
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"Ok", nil];
[alert autorelease];
// validate the username and token
if(![self isValid])
{
// show alert that it is not valid
alert.message = #"Invalid User Name or Password";
[alert show];
return;
}
BOOL isSynched = [self syncSettings];
if(!isSynched)
{
alert.message = #"Error Syncing Settings";
}
else
{
alert.title = #"";
alert.message = #"Settings has been Synced Syncing";
}
[alert show];

Try leaving all those instances of [alert show]; out & then at the end put...
if (!alert) return;
[alert show];
phix23's answer also provides good improvement because you're setting a bunch of the properties of the alert explicitly & only once. If you use that you can also use mine by changing the condition to...
if (alert.message != #"") return;
Cheers, Pedro :)

Related

Lat,Long values are not accurate to the current location in iphone

I am new to IOS now I am developing location app i am not getting correct latitude,longitude values while running my app in iPhone.. it gives me too far lat,long values to the current location why it shows me these values can anyone tell me..
Try it....
Set Delegate CLLocationManagerDelegate
#import <CoreLocation/CoreLocation.h>
CLLocationManager *locationManager;
CLLocation *startLocation;
- (void)viewDidLoad {
[super viewDidLoad];
NSString *currentLatitude;
NSString *currentLongitude;
locationManager = [[CLLocationManager alloc] init];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.delegate = self;
[locationManager startUpdatingLocation];
startLocation = nil;
}
-(void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
currentLatitude = [[NSString alloc]
initWithFormat:#"%g",
newLocation.coordinate.latitude];
currentLongitude = [[NSString alloc]
initWithFormat:#"%g",
newLocation.coordinate.longitude];
NSLog(#"%#",currentLatitude);
NSLog(#"%#",currentLongitude);
}
-(void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"ERROR" message:[NSString stringWithFormat:#"%#",error] delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
[alert release];
}

Not able to retrieve data from database in ios

I want to save some data into sqlite database and the read it, there is no problem while saving the data but i am not able to retrieve data from database.
Here is the code that I'm using.
//>>>>>> to save in sqlite Database
-(void)saveData
{
NSString *strTxtFldValue = txtFldName.text;
sqlite3_stmt *statement;
const char *dbpath = [appDel.databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat:#"INSERT INTO TESTTABLE (NAME) VALUES (\"%#\")",strTxtFldValue];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(database, insert_stmt,
-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSLog(#"Data is added succesfully ");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Confirmation" message:#"Name is added successfully." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
} else {
NSLog(#"Failed to add data");
}
sqlite3_finalize(statement);
sqlite3_close(database);
}
}
//>>>>>> to read from database
//here the control comes till second NSLog and the "sqlite3_prepare_v2" statement doesn't get execute.
-(void)readData{
const char *dbpath = [appDel.databasePath UTF8String];
sqlite3_stmt *statement;
NSLog(#"^^^^^^^ 1");
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSLog(#"^^^^^^^ 2");
// NSString *querySQL = [NSString stringWithFormat:#"SELECT * FROM TESTTABLE"];
NSString *querySQL = [NSString stringWithFormat:#"SELECT NAME FROM TESTTABLE"];
const char *query_stmt = [querySQL UTF8String];
**if (sqlite3_prepare_v2(database,query_stmt, -1, &statement, NULL) == SQLITE_OK)**
{
NSLog(#"^^^^^^^ 3");
while(sqlite3_step(statement) == SQLITE_ROW)
{
NSLog(#"^^^^^^^ 4");
NSString *cName = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
NSLog(#"~~~~### cName = %#",cName);
Names *name = [[Names alloc] initWithName:cName];
[names addObject:name];
[name release];
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
}
}
Please provide the solution.
Thanks in advance
Create the database at runtime, and use the below logic,
to write the data in sqlite.
sqlite3 *pDb;
char *databaseName;
databaseName = #"TempDatabase.sql";
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
//databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
databasePath =[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"TempDatabase.sql"];
//[self copyDatabaseIfNeeded];
if(sqlite3_open([databasePath UTF8String], &pDb) == SQLITE_OK)
{
const char *sqlStatement = "INSERT INTO tablename (name) VALUES(?)";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(pDb, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
{
sqlite3_bind_text( compiledStatement, 1, [strTxtFldValue UTF8String], -1, SQLITE_TRANSIENT);
}
if(sqlite3_step(compiledStatement) != SQLITE_DONE )
{
NSLog( #"~~~~~~~~~~~ 1 Error: %s", sqlite3_errmsg(pDb) );
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Name name is not added." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Confirmation" message:#"name is added successfully." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(pDb);
To read data from sqlite
sqlite3 *database;
const char *dbpath = [appDel.databasePath UTF8String];
sqlite3_stmt *statement;
NSMutableArray *names = [[NSMutableArray alloc]init];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
const char *sqlStatement = "select name from tablename";
if (sqlite3_prepare_v2(database, sqlStatement, -1, &statement, NULL) == SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *cName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement,0)];
//NSLog(#"cName = %#",cName);
Names *name = [[Names alloc] initWithName:cName];
[names addObject:name];
[name release];
}
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
Try out this and vote me if it works fine for you.

Not able to launch msn using url schema

I want to launch MSN through my iphone App.
I am using url shema-
BOOL msn = [[UIApplication sharedApplication] openURL:[NSURL URLWithString:#"msnim://"]];
if (msn) {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:#"msnim://"]];
}
else {
UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle: #"MSN not Installed" message: nil delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
[errorAlert release];
but its not working.
Am i using wrong custom url for MSN????
If yes,then what is the url scheme for MSN.

Trying to pop a UIAlert if my search predicate returns nil

I'm trying to pop an alert that says "No records found" if the user does a search and the predicate returns nil.
I tried this, but the alert never gets called. I just get an empty tableview.
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
if (self.sBar.text != nil){
NSPredicate *template = [NSPredicate predicateWithFormat:#"name contains[cd] $SEARCH OR optionOne contains[cd] $SEARCH OR optionTwo contains[cd] $SEARCH"];
NSDictionary *replace = [NSDictionary dictionaryWithObject:self.sBar.text forKey:#"SEARCH"];
NSPredicate *predicate = [template predicateWithSubstitutionVariables:replace];
[fetchedResultsController.fetchRequest setPredicate:predicate];
}
[[fetchedResultsController fetchedObjects] count];
if (fetchedResultsController.fetchedObjects != nil) {
//do nothing
} else {
//display alert
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:#"No records match."
delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
NSError *error = nil;
if (![[self fetchedResultsController] performFetch:&error]) {
// Handle error
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort(); // Fail
}
[self.myTable reloadData];
[sBar resignFirstResponder];
}
A predicate does not have a -count. A predicate is an expression that evaluates to true or false. That's it.
You can ask the NSFetchedResultsController for its -fetchedObjects (which returns an array), and then ask that array for its -count, but you can only do this after you invoke -performFetch:.
Ha ha! Got it...
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
if (self.sBar.text != nil) {
NSPredicate *template = [NSPredicate predicateWithFormat:#"name contains[cd] $SEARCH OR optionOne contains[cd] $SEARCH OR optionTwo contains[cd] $SEARCH"];
NSDictionary *replace = [NSDictionary dictionaryWithObject:self.sBar.text forKey:#"SEARCH"];
NSPredicate *predicate = [template predicateWithSubstitutionVariables:replace];
[fetchedResultsController.fetchRequest setPredicate:predicate];
}
NSError *error = nil;
if (![[self fetchedResultsController] performFetch:&error]) {
// Handle error
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
exit(-1); // Fail
}
if ([[fetchedResultsController fetchedObjects] count] != 0) {
[self.myTable reloadData];
[sBar resignFirstResponder];
}
else {
//display alert
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:#"No records match."
delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
}

UIAlertView backgroundImage

How can i set a background image in a UIAlertView progrmatically?
There is no method to set the background image for AlertView. We need to set image as subView for alert View.
Try this way it will work:
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Title" message:#"Message 1......\nMessage 2......" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
UIImageView *Image =[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"ImageName"]];
[alert addSubview:Image];
[Image release];
[alert show];
[alert release];
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"title" message:#"Empty data not Allowed" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:nil];
UIImage *alertImage = [UIImage imageNamed:#"custom-dialog-background.png"];
UIImageView *backgroundImageView = [[UIImageView alloc] initWithImage:alertImage];
backgroundImageView.frame = CGRectMake(0, 0, 282, 130);
backgroundImageView.contentMode = UIViewContentModeScaleToFill;
[alert addSubview:backgroundImageView];
[alert sendSubviewToBack:backgroundImageView];
[alert show];

Resources