Value Stored to during its initialization is never read - iphone

float latitude = [((IPADAppDelegate *)[UIApplication sharedApplication].delegate).detailViewController.userStoreInfoObj.StoreLatitude floatValue];
float longitude = [((IPADAppDelegate *)[UIApplication sharedApplication].delegate).detailViewController.userStoreInfoObj.StoreLongitude floatValue];
NSString *strAddress = [((IPADAppDelegate *)[UIApplication sharedApplication].delegate).detailViewController.userStoreInfoObj StoreAddress];
NSString *strCountry= [((IPADAppDelegate *)[UIApplication sharedApplication].delegate).detailViewController.userStoreInfoObj StoreCounty];
NSString *strCode = [((IPADAppDelegate *)[UIApplication sharedApplication].delegate).detailViewController.userStoreInfoObj StoreZip];
if(storeData)
{
latitude = [storeInfoObj.StoreLatitude floatValue];
longitude = [storeInfoObj.StoreLongitude floatValue];
strAddress = [storeInfoObj StoreAddress];
strCountry = [storeInfoObj StoreCounty];
strCode = [storeInfoObj StoreZip];
}
Value stored to latitude during its initialization is never read.
Can anyone help me understand why this is happening?
What can I do to fix this? Please help me out [I try my luck].
# Thanks in advance

one example: the static analyzer has likely detected that storeData will always evaluate to true:
StoreData * storeData = thing.storeData;
if (!storeData) {
/* get out of here!!! */
return;
}
IPADAppDelegate * appDelegate = (IPADAppDelegate*)[UIApplication sharedApplication].delegate;
UserStoreInfoObj * userStoreInfoObj = appDelegate.detailViewController.userStoreInfoObj;
float latitude = [userStoreInfoObj.StoreLatitude floatValue];
float longitude = [userStoreInfoObj.StoreLongitude floatValue];
NSString *strAddress = [userStoreInfoObj StoreAddress];
NSString *strCountry= [userStoreInfoObj StoreCounty];
NSString *strCode = [userStoreInfoObj StoreZip];
if (storeData) << would be redundant and always true
{
latitude = [storeInfoObj.StoreLatitude floatValue]; << why not initialize latitude using this value???
longitude = [storeInfoObj.StoreLongitude floatValue];
strAddress = [storeInfoObj StoreAddress];
strCountry = [storeInfoObj StoreCounty];
strCode = [storeInfoObj StoreZip];
}
but you can significantly reduce the complexity of this program (to read, maintain, and execute) by using something like this:
UserStoreInfoObj * storeInfo = nil;
if (storeData) storeInfo = storeInfoObj;
else storeInfo = ((IPADAppDelegate *)[UIApplication sharedApplication].delegate).detailViewController.userStoreInfoObj;
float latitude = [storeInfo.StoreLatitude floatValue];
float longitude = [storeInfo.StoreLongitude floatValue];
NSString *strAddress = [storeInfo StoreAddress];
NSString *strCountry= [storeInfo StoreCounty];
NSString *strCode = [storeInfo StoreZip];

Related

Google maps API error: "stringwithcontentsofurl is deprecated"

I have code that keeps giving me an "stringwithcontentsofurl is deprecated" error and I can't figure out how to fix it. The app keeps taking me to google maps and showing the center of the ocean at 0.0 lat, 0.0 long. This is the code I have now...
NSString *locationStr = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlStr]];
NSLog(#"locationstr:%#",locationStr);
NSArray *items = [locationStr componentsSeparatedByString:#","];
double lat = 0.0;
double lon = 0.0;
if([items count] >= 4 && [[items objectAtIndex:0] isEqualToString:#"200"]) {
lat = [[items objectAtIndex:2] doubleValue];
lon = [[items objectAtIndex:3] doubleValue];
} else {
NSLog(#"Address, %# not found: Error %#",addressStr, [items objectAtIndex:0]);
}
NSLog(#"latlonislatlon:%.12f,%.12f,urlstr:%#",lat,lon,urlStr);
CLLocationCoordinate2D location;
location.latitude = lat;
location.longitude = lon;
thanks for the help!
Because your variables have been set to 0.0 for latitude and longitude.
Use this to remove deprecation warning
NSString *locationStr = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlStr] encoding:NSUTF16BigEndianStringEncoding error:nil];
Also try using different lat, long since their might be problem with your lat long
It has been replaced with
stringWithContentsOfURL:encoding:error:
or
stringWithContentsOfURL:usedEncoding:error:

Assigning lat long to CLLocation giving error not accepting any format

I am giving lat long to CLLocation in this way.
CLLocation *loc = [[CLLocation alloc]init];
loc.coordinate.latitude = [sLat floatValue];
loc.coordinate.longitude = [sLng floatValue];
Coming from
NSMutableDictionary *locat = [dictLoc valueForKey:#"location"];
sLat = [locat valueForKey:#"lat"];
sLng = [locat valueForKey:#"lng"];
Showing correct values in console, but kills when allocated to cllocation.
Please guide for the above.
Thanks.
you can get the value in CLLocationCoordinate2D object like bellow...
CLLocationCoordinate2D location;
location.latitude = [sLat doubleValue];
location.longitude = [sLng doubleValue];
OR Also try to retain that string like bellow..
sLat = [locat valueForKey:#"lat"];
[sLat retain];
sLng = [locat valueForKey:#"lng"];
[sLng retain];
and then assign it to CLLocation
hope this helpful to you....

to get float values of latitude and longitude from database

I am trying to get the latitude and longitude of certain regions stored in my database and to store them in an array. I have to store the values as float types. I am getting other values by the following code:
NSString *walkQuery = [[NSString alloc] initWithFormat:#"SELECT Wid,WName,SName,Latitude,Longitude from Walks,SubRegions WHERE Walks.Sid=SubRegions.Sid AND Rid = %d",[regionId integerValue] ];
sqlite3_stmt *walkstatement = nil;
if (sqlite3_prepare_v2(walkNameDB,[walkQuery UTF8String], -1, &walkstatement, nil) == SQLITE_OK)
{
while( sqlite3_step(walkstatement) == SQLITE_ROW )
{
NSNumber *WId;
int temp1 = (int)sqlite3_column_int(walkstatement, 0);
WId = [[NSNumber alloc] initWithInt:temp1];
char *WNameCharacter;
WNameCharacter = (char *) sqlite3_column_text(walkstatement, 1);
NSString *WNameString = [[NSString alloc] initWithUTF8String:WNameCharacter];
char *SNameCharacter;
SNameCharacter = (char *) sqlite3_column_text(walkstatement, 2);
NSString *SNameString = [[NSString alloc] initWithUTF8String:SNameCharacter];
NSMutableDictionary *tempWalk = [[NSMutableDictionary alloc] init];
[tempWalk setObject:WId forKey:#"WalkId"];
[tempWalk setObject:WNameString forKey:#"WalkName"];
[tempWalk setObject:SNameString forKey:#"SubRegionName"];
[regionWalkArray addObject:tempWalk];
Is their any way by which I can get the two float values of latitude and longitude also like I am doing in my code?
Please suggest....
You can use:
float latitude = (float) sqlite3_column_double(walkstatement, 3);
float longitude = (float) sqlite3_column_double(walkstatement, 4);
And can store in dictionary like:
[tempWalk setObject:[NSNumber numberWithFloat:latitude] forKey:#"latitude"];
[tempWalk setObject:[NSNumber numberWithFloat:longitude] forKey:#"longitude"];
You can retrieve it like:
float latitude = [[tempWalk objectForKey:#"latitude"] floatValue];
float longitude = [[tempWalk objectForKey:#"longitude"] floatValue];

iPhone: Sorting based on location

I have been working on an iPhone app, where-in i have list of users in a NSMutableArray like below.
myMutableArray: (
{
FirstName = Getsy;
LastName = marie;
Latitude = "30.237314";
Longitude = "-92.461008";
},
{
FirstName = Angel;
LastName = openza;
Latitude = "30.260329";
Longitude = "-92.450414";
},
{
FirstName = Sara;
LastName = Hetzel;
Latitude = "30.2584499";
Longitude = "-92.4135357";
}
)
I need to sort users based on the location who is nearby to my location by calculating latitude and longitude. I am not able to achieve this till now. Could someone help me on giving some samples?
UPDATED: I am trying like below as per Mr.sch suggested. Please check my updated code. Is it fine?.
NSArray *orderedUsers = [myMutableArray sortedArrayUsingComparator:^(id a,id b) {
NSArray *userA = (NSArray *)a;
NSArray *userB = (NSArray *)b;
CGFloat aLatitude = [[userA valueForKey:#"Latitude"] floatValue];
CGFloat aLongitude = [[userA valueForKey:#"Longitude"] floatValue];
CLLocation *participantALocation = [[CLLocation alloc] initWithLatitude:aLatitude longitude:aLongitude];
CGFloat bLatitude = [[userA valueForKey:#"Latitude"] floatValue];
CGFloat bLongitude = [[userA valueForKey:#"Longitude"] floatValue];
CLLocation *participantBLocation = [[CLLocation alloc] initWithLatitude:bLatitude longitude:bLongitude];
CLLocation *myLocation = [[CLLocation alloc] initWithLatitude:locationCoordinates.latitude longitude:locationCoordinates.longitude];
CLLocationDistance distanceA = [participantALocation distanceFromLocation:myLocation];
CLLocationDistance distanceB = [participantBLocation distanceFromLocation:myLocation];
if (distanceA < distanceB) {
return NSOrderedAscending;
} else if (distanceA > distanceB) {
return NSOrderedDescending;
} else {
return NSOrderedSame;
}
}];
Thank you!
NSArray *orderedUsers = [users sortedArrayUsingComparator:^(id a,id b) {
User *userA = (User *)a;
User *userB = (User *)b;
CLLocationDistance distanceA = [userA.location getDistanceFromLocation:myLocation];
CLLocationDistance distanceB = [userB.location getDistanceFromLocation:myLocation];
if (distanceA < distanceB) {
return NSOrderedAscending
} else if (distanceA > distanceB) {
return NSOrderedDescending;
} else {
return NSOrderedSame;
}
}];
First thing, you will need to calculate the distance between your current location and the location of each other user.
Talking mathematically, here is a Wolfram|Alpha example
Now "programmatic-ally", you can use CLLocation class, here is an example:
(CLLocationDistance)getDistanceFrom:(const CLLocation *)location
But first you will need to create the location object from your Latitude and Longitude. You can use:
(id)initWithLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude
You can calculate the distance (geographical, not flat plane!) between your position and each of these items' positions and order by that value.
- (void)viewDidLoad {
[super viewDidLoad];
// This Array Taken Globally
List_of_locationsArray =[[NSMutableArray alloc]initWithObjects:
#{#"latitude" : #"17.415045",#"logitude":#"78.421424"} ,#{#"latitude" : #"17.415045",#"logitude":#"78.421424"},#{#"latitude" : #"17.415045",#"logitude":#"78.421424"},#{#"latitude" : #"17.415045",#"logitude":#"78.421424"},#{#"latitude" : #"17.415045",#"logitude":#"78.421424"}
,nil];
}
-(void)sortingLocationsArray{
// CLLocation* currentLocation =[[CLLocation alloc]initWithLatitude:[currentLatitude doubleValue] longitude:[currentLogitude doubleValue]];
CLLocation* currentLocation =[[CLLocation alloc]initWithLatitude: currentLatitudeHere longitude:CurrentLogHere];
NSMutableArray* tempLocationsArr = [[NSMutableArray alloc]initWithCapacity:[locationsArray count]];
for (int i=0; i<[locationsArray count]; i++) {
CLLocationDegrees latValue = [[locationsArray[i] objectForKey:#"latitude"] doubleValue];
CLLocationDegrees longValue = [[locationsArray[i] objectForKey:#"logitude"] doubleValue];
CLLocation* location = [[CLLocation alloc]initWithLatitude:latValue longitude:longValue];
[tempLocationsArr addObject:location];
NSArray* sortLocationArry = [tempLocationsArr sortedArrayUsingComparator:^NSComparisonResult(CLLocation* location1, CLLocation* location2) {
CLLocationDistance distA = [location1 distanceFromLocation:currentLocation];
CLLocationDistance distB = [location2 distanceFromLocation:currentLocation];
if (distA < distB) {
return NSOrderedAscending;
} else if ( distA > distB) {
return NSOrderedDescending;
} else {
return NSOrderedSame;
}
}];
//ArrayAfterSorting is another mutable Array to Store Sorting Data
[ArrayAfterSorting removeAllObjects];
[sortLocationArry enumerateObjectsUsingBlock:^(CLLocation* location, NSUInteger idx, BOOL *stop) {
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc]init];
[tempDict setObject:[NSString stringWithFormat:#"%f",location.coordinate.latitude] forKey:#"latitude"];
[tempDict setObject:[NSString stringWithFormat:#"%f",location.coordinate.longitude] forKey:#"logitude"];
[ArrayAfterSorting addObject:tempDict];
}];
NSLog(#"sortedArray : %#", ArrayAfterSorting);
}
}
You may solve your problem in following way
1)Firstly store all above values in separate array Like latArray ,longArray,nameArray
2)Now get the distance between location(longArray,latArray) from your current location.
Then store these distances in separate Array(distanceArray).
//getDistance Between currentLocation and desired Location
-(void *)getDistanceFromCurrentLocation{
for(int val=0;val<[latArray count];val++){
NSString *dis_From_Current_Location;
dis_From_Current_Location =nil;
CGFloat str_Longitude=[[defaults objectForKey:#"long"]floatValue];
CGFloat str_Latitude=[[defaults objectForKey:#"lati"]floatValue];
//Suppose this is your current location
CGFloat lat1= [[latArray objectAtIndex:val]floatValue];
//these array for lat
CGFloat long1=[[longArray objectAtIndex:val]floatValue];
//these array for longArray
CLLocation *location1 = [[CLLocation alloc] initWithLatitude:lat1 longitude:long1];
CLLocation *location2 = [[CLLocation alloc] initWithLatitude:str_Latitude longitude:str_Longitude];
CLLocationDistance dist=[location1 distanceFromLocation:location2];
NSLog(#"Distance i meters: %f", [location1 distanceFromLocation:location2]);
long long v = llabs(dist/1000);
dis_From_Current_Location=[NSString stringWithFormat:#"%lld km",v];
[location1 release];
[location2 release];
[distanceArray addObject: dis_From_Current_Location];
//distanceArray is Global NsMutableArray.
}
}
Now You should Apply sorting method(selection, bubble) fro sorting the distances.
One thing need to care is that when you sort the distanceArray
please adjust values of nameArray as according to the distanceArray
See Below code for sorting the distanceArray and adjust the nameArray's value.
-(void)getSoretdArray{
NSString * tempStr,*tempStr2;
for(int i=0;i<[distanceArray count]; i++){
for(int j=i+1;j<[distanceArray count]; j++){
if([distanceArray objectAtIndex:j]>[distanceArray objectAtIndex:j+1]){
tempStr=[distanceArray objectAtIndex:j];
NSString* str= [distanceArray objectAtIndex:j+1];
[ distanceArray insertObject:str atIndex:j];
[distanceArray insertObject:tempStr atIndex:j+1] ;
//also change the name of corresponding location.
//you have to adjust the stored names in namArray for storing names of Corresponding Distances
tempStr2=[nameArray objectAtIndex:j];
NSString* str1= [nameArray objectAtIndex:j+1];
[ nameArray insertObject:str1 atIndex:j];
[nameArray insertObject:tempStr2 atIndex:j+1] ;
}
}
}
}
This will definitely work just try to use carefully

OBJ-C: Getting the minimum/maximum value in a NSMutableArray

I want to get the maximum and minimum values of a NSMutableArray so I can create a core-plot plotspace and graph based around those max and min values.
My code is as follows:
NSMutableArray *contentArray = [NSMutableArray arrayWithCapacity:100];
NSUInteger i;
for (i=0; i<60; i++){
id x = [NSNumber numberWithFloat:i*0.05];
id y = [NSNumber numberWithFloat:1.2*rand()/(float)RAND_Max + 0.6];
[contentArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:x, #"x", y, #"y", nil]];
}
self.dataForPlot = contentArray;
CPXYPlotSpace *plotSpace = (CPXYPlotSpace *)graph.defaultPlotSpace;
plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat() length:CPDecimalFromFloat()];
plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat() length:CPDecimalFromFloat()];
What do I fill in the blanks for xRange and yRange assignment if I want the graph to span only the space of what's specified in contentArray?
In this case, you should use -[CPPlotSpace scaleToFitPlots:]. For more general calculations on array values, read on...
This is an ideal use for Key-Value coding and associated array operators. In your example,
float maxX = [[contentArray valueForKeyPath:#"#max.x"] floatValue];
float minY = [[contentArray valueForKeyPath:#"#min.x"] floatValue];
float maxY = [[contentArray valueForKeyPath:#"#max.y"] floatValue];
float minY = [[contentArray valueForKeyPath:#"#min.y"] floatValue];
The array operators call valueForKeyPath: on the contentArray which gives an array built by calling the same valueForKeyPath: on each member of the array with the key path to the right of the array operator (i.e. #min and #max). The orignal call then applies the given operator to the resulting array. You could easily define a category on NSArray to give you back a struct of min/max values:
typedef struct {
float minX;
float minY;
float maxX;
float maxY;
} ArrayValueSpace;
#implementation NSArray (PlotSpaceAdditions)
- (ArrayValueSpace)psa_arrayValueSpace {
ArrayValueSpace result;
result.maxX = [[contentArray valueForKeyPath:#"#max.x"] floatValue];
result.minX = [[contentArray valueForKeyPath:#"#min.x"] floatValue];
result.maxY = [[contentArray valueForKeyPath:#"#max.y"] floatValue];
result.minY = [[contentArray valueForKeyPath:#"#min.y"] floatValue];
return result;
}
You can find max and min values when you fill it, but it would work just when used in your snippet. If you want something more generic you should simply go through the list and searching for it.
// contentArray already defined
int maxX = 0, minX = 1000, maxY = 0, minY = 1000;
for (int i = 0; i < [contentArray count]; ++1)
{
int curX = [[[contentArray objectForKey:#"x"] objectAtIndex:i] integerValue];
int curY = [[[contentArray objectForKey:#"y"] objectAtIndex:i] integerValue];
if (curX < minX)
minX = curX;
else if (curX > maxX)
maxX = curX;
if (curY < minY)
minY = curY;
else if (curY > maxY)
maxY = curY;
}
You could use fast enumeration through the array.
.
NSUInteger maxX = 0;
NSUInteger minX = 0xFFFFFFFF; //(for 32 bit)
NSUInteger maxY = 0;
NSUInteger minY = 0xFFFFFFFF; //(for 32 bit)
for ( NSDictionary *dict in contentArray )
{
NSUInteger newX = [[dict objectForKey:#"x"] integerValue];
NSUInteger newY = [[dict objectForKey:#"y"] integerValue];
if (maxX > newX) maxX = newX;
if (minX > newX) minX = newX;
if (maxY > newY) maxY = newY;
if (minY > newY) minX = newY;
}
if you have NSMutableArray of NSDictionary objects you can use this:
-(float)findMax:array arrayKey:obj {
float max = [[[array objectAtIndex:0] objectForKey:obj] floatValue];
for ( NSDictionary *dict in array ) {
if(max<[[dict objectForKey:obj] floatValue])max=[[dict objectForKey:obj] floatValue];
}
return max;
}
-(float)findMin:array arrayKey:obj {
float min = [[[array objectAtIndex:0] objectForKey:obj] floatValue];
for ( NSDictionary *dict in array ) {
if (min > [[dict objectForKey:obj] floatValue])min = [[dict objectForKey:obj] floatValue];
}
return min;
}
You would access methods like this if in another class:
GraphData *c=[[GraphData alloc] init];
float maxY=[c findMax:plotData arrayKey:[NSNumber numberWithInt:1]]; //1 or 0 depending on axis
[c release];
//This gives Max and Min Value in NSMutableArrray
-(void)FindingMinAndMaxValueInNSMutableArray{
NSMutableArray *array=[[NSMutableArray alloc]initWithObjects:#"0.987",#"0.951",#"0.881",#"0.784",#"0.662",#"0.522",#"0.381",#"-0.265",#"-0.197", #"0.189",#"-0.233",#"0.310",#"0.402",#"0.402",#"0.988",#"0.633",#"0.661",#"0.656",#"0.617",#"0.634",#"0.690",#"0.767",#"0.836",nil];
NSLog(#"The Array Value is %#",array);
NSLog(#"The Array Count is %lu",(unsigned long)array.count);
NSNumber *maxValue = [array valueForKeyPath:#"#max.doubleValue"];
NSLog(#"The maxValue is %#",maxValue);
NSString *str=[NSString stringWithFormat:#"%#",maxValue];
NSInteger path=[array indexOfObject:str];
NSIndexPath *indexpath=[NSIndexPath indexPathForItem:path inSection:0];
NSLog(#"Max Value = %# and index = %ld",maxValue,(long)indexpath.row);
NSNumber *minValue = [array valueForKeyPath:#"#min.doubleValue"];
NSLog(#"The minValue is %#",minValue);
NSString *str1 = [NSString stringWithFormat:#"%#",minValue];
NSInteger path1 = [array indexOfObject:str1];
NSIndexPath *indexPath1 = [NSIndexPath indexPathForItem:path1 inSection:0];
NSLog(#"Min Value =%# and index = %ld",minValue,(long)indexPath1.row);
}