TextView with multiple result - iphone

I Have something like that:
for(MKMapItem *mapItem in response.mapItems){
MKPlacemark *placeMark = mapItem.placemark;
NSLog(#"showSearchResponse: mapItem = %# coordinate = %g,%g \nname = %#\naddressDictionary = %#",
mapItem,
placeMark.coordinate.latitude,
placeMark.coordinate.longitude,
mapItem.name,
placeMark.addressDictionary);
[self.mapView addAnnotation:placeMark];
scrollText.editable=NO;
scrollText.scrollEnabled = YES;
scrollText.text = [NSString stringWithFormat:#"%#",placeMark.addressDictionary];
i want to list all the results in TextView, this code showed me only last result
Thx for help !

The problem is at the end of your loop:
scrollText.text = [NSString stringWithFormat:#"%#",placeMark.addressDictionary];
You are resetting the text to the last entry.
So you have two options. Once of them is just concatenate a string with your results and set that as the text for your scrollText or concatenate the string over scrolText like this
scrollText.text = [NSString stringWithFormat:#"%#%#",scrollText.text, placeMark.addressDictionary];

You are re-setting value of scrollText each time. So try this one:
NSMutableString *resultString = [[NSMutableString alloc]init];
for(MKMapItem *mapItem in response.mapItems){
MKPlacemark *placeMark = mapItem.placemark;
NSLog(#"showSearchResponse: mapItem = %# coordinate = %g,%g \nname = %#\naddressDictionary = %#",
mapItem,
placeMark.coordinate.latitude,
placeMark.coordinate.longitude,
mapItem.name,
placeMark.addressDictionary);
[self.mapView addAnnotation:placeMark];
[resultString appendFormate:#"%#\n",placeMark.addressDictionary];
}
scrollText.editable=NO;
scrollText.scrollEnabled = YES;
scrollText.text = resultString;
I hope this will be useful.

Related

How to add elements to an array created by a 'for' loop ?

I am using for loop for get distance from current location to destination location. I would like an array that contains all distances from current to destination location.
for (i = 0; i < [Arr_Lat count]; i++)
{
NSString *latst1 = [[NSString alloc]initWithFormat:[Arr_Lat objectAtIndex:i]];
NSString *longst1 = [[NSString alloc]initWithFormat:[Arr_Long objectAtIndex:i]];
NSLog(#"First lat : %#",latst1);
NSLog(#"First ong : %#",longst1);
double Doblat1 = [latst1 doubleValue];
double Doblong1 = [longst1 doubleValue];
CLLocationCoordinate2D coord1 = CLLocationCoordinate2DMake(coord1.latitude = Doblat1, coord1.longitude = Doblat1);
NSLog(#" Coordinat ==== : %f -- %f",coord1.latitude,coord1.longitude) ;
CLLocation *currLoc = [[CLLocation alloc] initWithLatitude:appDel.curr_lat longitude:appDel.curr_long];
CLLocation *destLoc1 = [[CLLocation alloc] initWithLatitude:Doblat1 longitude:Doblong1];
NSLog(#" Currennt Location : %#", currLoc);
NSLog(#" Destination Location : %#" , destLoc1);
distance = [destLoc1 distanceFromLocation:currLoc];
NSLog(#" Distance : ------- %0.3f", distance);
DistStr = [[NSString alloc]initWithFormat:#" %f",distance];
[currLoc release];
[destLoc1 release];
[Arr_title retain];
[tbl_nearplace reloadData];
}
If you want to store the distance you need an NSMutableArray.
Declare a NSMutableArray *distanceArray; in class scope.
Initialize it: distanceArray = [[NSMutableArray alloc] init];
In the for loop after DistStr =[[NSString alloc]initWithFormat:#" %f",distance];
write the following code:
[distanceArray addObject:DistStr];
Say we have this array with stuff we want to iterate over and add those items to another array
NSArray *someArrayWithStuff = #[#"Hello",
#"Its",
#"Very",
#"Cold",
#"Outside",
#"Today"];
Say we want the content of someArrayWithStuff to be added to this other array so we create an NSMutableArray
NSMutableArray *theNewArrayWithOurStuff = [NSMutableArray array];
We loop through the someArrayWithStuff
for (int i = 0; i < someArrayWithStuff.count; i++) {
// Add object to the new array
[theNewArrayWithOurStuff addObject:[someArrayWithStuff objectAtIndex:i]];
}
NSMutableArray *Distance=[[NSMutableArray alloc]Init];
for (i = 0; i < [Arr_Lat count]; i++)
{
NSString *latst1 = [[NSString alloc]initWithFormat:[Arr_Lat objectAtIndex:i]];
NSString *longst1 = [[NSString alloc]initWithFormat:[Arr_Long objectAtIndex:i]];
NSLog(#"First lat : %#",latst1);
NSLog(#"First ong : %#",longst1);
double Doblat1 = [latst1 doubleValue];
double Doblong1 = [longst1 doubleValue];
CLLocationCoordinate2D coord1 = CLLocationCoordinate2DMake(coord1.latitude = Doblat1, coord1.longitude = Doblat1);
NSLog(#" Coordinat ==== : %f -- %f",coord1.latitude,coord1.longitude) ;
CLLocation *currLoc = [[CLLocation alloc] initWithLatitude:appDel.curr_lat longitude:appDel.curr_long];
CLLocation *destLoc1 = [[CLLocation alloc] initWithLatitude:Doblat1 longitude:Doblong1];
NSLog(#" Currennt Location : %#", currLoc);
NSLog(#" Destination Location : %#" , destLoc1);
distance = [destLoc1 distanceFromLocation:currLoc];
NSLog(#" Distance : ------- %0.3f", distance);
NSString *DistStr = [[NSString alloc]initWithFormat:#" %f",distance];
[Distance addObject:DistStr];
[DistStr release];
[currLoc release];
[destLoc1 release];
[Arr_title retain];
[tbl_nearplace reloadData];
}

NSCFString objectForKey unrecognized selector sent to instance

//initialize the people data list
- (void)initializePeopleListFromJson:(CLLocationCoordinate2D)coordinate auraId:(NSString *)auraId
{
//initialize the NSMutableArray list
self.peopleList = [[NSMutableArray alloc] init];
//retrieve the coordinate of myself
//NSString *myCoordinate = [NSString stringWithFormat:#"%f,%f", coordinate.latitude, coordinate.longitude];
NSString *myCoordinate = #"31.2,121.6";
NSString *url = [NSString stringWithFormat:#"%#%#%#%#", #"http://services.portaura.mobi/AuraMesh/auraFinder/findPeoples?ll=", myCoordinate, #"&source=tencent,netease,kaixin&myAuraId=", auraId];
NSLog(#"*********** %#", url);
//retrieve the people list from web service
NSDictionary* result = [NSDictionary dictionaryWithContentsOfJSONURLString:url];
NSArray *peopleListFromJson = [result objectForKey:#"data"];
// NSLog(#"peopleList: %#", peopleListFromJson);
People *people;
UserProfile *userProfile;
NSDictionary *geoFromJson;
NSDictionary *profileFromJson;
for (NSDictionary *peopleFromJson in peopleListFromJson)
{
people = [[People alloc] init];
userProfile = [[UserProfile alloc] init];
people.foreignId = [peopleFromJson objectForKey:#"foreignId"];
people.id1 = [peopleFromJson objectForKey:#"id"];
people.isFavorited = [peopleFromJson objectForKey:#"isFavorited"];
people.lastActiveTime = [peopleFromJson objectForKey:#"lastActiveTime"];
people.lastActivity = [peopleFromJson objectForKey:#"lastActivity"];
people.lastPlace = [peopleFromJson objectForKey:#"lastPlace"];
people.source = [peopleFromJson objectForKey:#"source"];
NSLog(#"AAAAAAAA %#", [peopleFromJson objectForKey:#"foreignId"]);
//process geo
geoFromJson = [[NSDictionary alloc] init];
geoFromJson = [peopleFromJson objectForKey:#"geo"];
CLLocationCoordinate2D coordinate;
coordinate.latitude = [[geoFromJson objectForKey:#"lat"] floatValue];
coordinate.longitude = [[geoFromJson objectForKey:#"lng"] floatValue];
people.geo = coordinate;
people.distance = [geoFromJson objectForKey:#"distance"];
//process profile
profileFromJson = [[NSDictionary alloc] init];
profileFromJson = [peopleFromJson objectForKey:#"profile"];
people.avatar = [profileFromJson objectForKey:#"avatar"];
people.gender = [profileFromJson objectForKey:#"gender"];
people.location = [profileFromJson objectForKey:#"location"];
people.screenName = [profileFromJson objectForKey:#"screenName"];
people.signature = [profileFromJson objectForKey:#"sigunature"];
//people.userProfile = userProfile;
[self addPeople:people];
}
}
it give me the [__NSCFString objectForKey:]: unrecognized selector sent to instance 0x1808d0,can you give some advice
json like :
{"status":0,"data":{"list":[{"foreignId":"8827857641648129226","geo":{"distance":1359,"lat":31.20926508184017,"lng":121.59068046014856},"id":"netease_8827857641648129226","isFavorited":false,"lastActiveTime":"2012-05-19T20:26:47Z","lastActivity":"Goal http://126.fm/kFEKl","lastPlace":"","profile":{"avatar":"http://oimagea3.ydstatic.com/image?w=48&h=48&url=http%3A%2F%2Fmimg.126.net%2Fp%2Fbutter%2F1008031648%2Fimg%2Fface_big.gif","gender":0,"location":"","screenName":"4671784460","sigunature":"","tags": []},"source":"netease"}......
check ur variable class peopleFromJson it might not be a dictionary at the moment you are calling objectForKey.
put this statement as first line in ur for loop
NSLog(#"%#",NSStringFromClass([peopleFromJson class]));
i have solved the problem,i cannot think the problem is easy,maybe some people only know the cause is the object is NSString not NSDir,but the real problem is depend on json "style",sometimes my code is correct,but for other json is not correct for example my question json. so solved is :
if ( ![peopleListFromJson isKindOfClass:[NSArray class]] && peopleListFromJson!=nil) {
peopleListFromJson =[NSArray arrayWithObject:peopleListFromJson];
}
because i used
NSDictionary* result = [NSDictionary dictionaryWithContentsOfJSONURLString:url];
NSArray *peopleListFromJson = [result valueForKeyPath:#"data.list"];
so peopleListFromJson!=nil is impotent

Objects added as subview to scrollview are not showing up

I am trying to add elements to a scroll view using this code:
int missionCount;
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *missionsDict = [responseString JSONValue];
/*NSArray *luckyNumbers = [json objectWithString:responseString error:&error];*/
NSLog(#"user Info array is: %#", missionsDict);
// NSDictionary *array = [luckyNumbers1 objectForKey:#"data"];
NSDictionary *missionsData;
missionsData = [missionsDict objectForKey:#"data"];
NSLog(#"missionsData is: %#", missionsData);
NSEnumerator *inner = [missionsData objectEnumerator];
missionsScroll.contentSize = CGSizeMake(768, 1005);
id value;
int badgeY1;
int badgeY2;
int badgeY3;
badgeY1 = 146;
badgeY2 = 188;
badgeY3 = 188;
while((value = [inner nextObject])) {
NSLog(#"value is: %#", value);
NSLog(#"progress is: %#", [value objectForKey:#"progress"]);
NSLog(#"user Info array is: %#", missionsDict);
NSLog(#"name is: %#",[value objectForKey:#"reward_definitions"]);
NSLog(#"missionsData is: %#", missionsData);
NSDictionary *moreData;
moreData = [value objectForKey:#"reward_definitions"];
NSEnumerator *inner2 = [moreData objectEnumerator];
id value2;
int badgeX;
int badgeCount;
badgeX = 0;
badgeCount = 0;
while((value2 = [inner2 nextObject])) {
UIProgressView *progressView;
progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(323, badgeY1, 372, 9)];
float progressValue;
progressValue = ([[[value objectForKey:#"progress"] objectForKey:#"earned"] floatValue] / [[[value objectForKey:#"progress"] objectForKey:#"possible"] floatValue]);
NSLog(#"progressValue is: %f", progressValue);
[progressView setProgress:progressValue];
[missionsScroll addSubview:progressView];
UILabel *missionName;
missionName = [[UILabel alloc] initWithFrame:CGRectMake(66, badgeY1, 227, 21)];
missionName.backgroundColor = [UIColor clearColor];
missionName.textColor = [UIColor whiteColor];
missionName.font = [UIFont fontWithName:#"Heiti TC" size:23.0];
missionName.text = [value objectForKey:#"name"];
[missionsScroll addSubview:missionName];
UILabel *requirementsLabel;
requirementsLabel = [[UILabel alloc] initWithFrame:CGRectMake(66, badgeY2+25, 227, 21)];
requirementsLabel.backgroundColor = [UIColor clearColor];
requirementsLabel.textColor = [UIColor whiteColor];
requirementsLabel.font = [UIFont fontWithName:#"Papyrus" size:19];
requirementsLabel.text = #"To complete you need:";
[missionsScroll addSubview:requirementsLabel];
NSLog(#"Image URL is: %#", [value2 objectForKey:#"image_url"]);
NSURL *url1 = [NSURL URLWithString: [NSString stringWithFormat:#"%#", [value2 objectForKey:#"image_url"]]];
NSData *urlData1 = [NSData dataWithContentsOfURL:url1];
UIImage *image1 = [UIImage imageWithData:urlData1];
UIImageView *badge = [[UIImageView alloc] initWithImage:image1];
[badge setFrame:CGRectMake(badgeX, badgeY2+70, 70, 70)];
[missionsScroll addSubview:badge];
[badge release];
badgeCount = badgeCount+1;
NSLog(#"badgeCount is: %i", badgeCount);
if (badgeCount == 4) {
NSLog(#"Badge Count = 4");
badgeY2 = badgeY2 +70;
badgeX = 0;
badgeCount = 0;
} else {
NSLog(#"Badge Count ≠ 4");
badgeX = badgeX +75;
}
}
NSLog(#"1st While loop done");
// NSLog(#"reward_definitions is: %#", [missionsData objectForKey:#"id"]);
// NSLog(#"Image URL is: %#", [[value objectForKey:#"reward_definitions"] objectForKey:#"image_url"]);
//if ( [array isKindOfClass:[NSDictionary class]] ) {
badgeY1 = badgeY1 +200;
badgeY2 = badgeY2 +200;
badgeY3 = badgeY3 +200;
missionCount = missionCount+1;
}
NSLog(#"While loops done");
for (int a; missionCount > 4; a = a+1) {
missionsScroll.contentSize = CGSizeMake(776, missionsScroll.contentSize.height+200);
}
Nothing is showing up in the scroll view.
It's not obvious what is happening, but first things to check are where the views are valid (not nil) and that this code is running on the main thread.
Put these in and post the results.
NSLog(#"missionsScroll: %#", (missionsScroll==nil)?#"NIL":#"OK");
NSLog(#"progressView: %#", (progressView==nil)?#"NIL":#"OK");
NSLog(#"missionName: %#", (missionName==nil)?#"NIL":#"OK");
NSLog(#"mainThread: %#", ([NSThread isMainThread])?#"OK":#"Background Thread");
Your code is quite convoluted and very difficult to read. Perhaps you could check if your complicated coordinates calculations work as expected, e.g.
NSLog(#"Frame of badge %#", NSStringFromCGRect(badge.frame));
How many times are your while loops iterating? The outer loop increases the y-position of your labels. But the labels will only be displayed at the end of the run loop / start of the next run loop. If you exit this method with the labels with a high y-value then you'll not see them. (It doesn't matter how many times you change the y-value while you're running this code. The display will only update when it's all done.)
** Correction ** You seem to be adding new views each time around your while loop. So in fact I'd expect you to have multiple copies of the subviews appearing when they finally get displayed.
(There's a lot of code to wade through here. If my answer is way off, you might get better answers, but trimming back some of the code and isolating the issue.)

cannot add another object into an array containing different objects

Someone please help.
I am a noob here who has just created an array to contain all my polyclinics object. Now I need to add in a user object (patientDetail object) into this array. But no matter how i modify the viewDidLoad method, something just seems not quite right.. i cannot populate all the points.. only when i remove all codes that deal with the user object then it works.. Some1 please take a look at the method below and advise? I need to add in the patientDetail object and populate it with the rest of the polyclinics...
thanks for reading =(
- (void)viewDidLoad {
[super viewDidLoad];
_annotation2 = [[NSMutableArray alloc] init];
CLLocation *userLoc = _mapView.userLocation.location;
CLLocationCoordinate2D userCoordinate = userLoc.coordinate;
NSLog(#"user latitude = %f",userCoordinate.latitude);
NSLog(#"user longitude = %f",userCoordinate.longitude);
_annotations=[[NSMutableArray alloc] init];
_listOfPolyClinics = [[NSMutableArray alloc] init];
PatientDetails *patientDetails = [[PatientDatabase database]
patientDetails:_nric];
for (PolyClinics *polyclinics in [[PatientDatabase database]
polyClinics]){
[_listOfPolyClinics addObject:polyclinics];
}
[_listOfPolyClinics addObject:patientDetails];
for (PolyClinics *polyclinics1 in _listOfPolyClinics){
MyAnnotation* myAnnotation=[[MyAnnotation alloc] init];
if ([polyclinics1 isKindOfClass:[PatientDetails class]]){
CLLocationCoordinate2D theCoordinate3;
theCoordinate3.longitude = patientDetails.longitude;
theCoordinate3.latitude = patientDetails.latitude;
myAnnotation.coordinate = theCoordinate3;
myAnnotation.title = _nric;
myAnnotation.subtitle = [NSString stringWithFormat:#"%i",patientDetails.category];
}
else{
CLLocationCoordinate2D theCoordinate;
theCoordinate.longitude = polyclinics1.longtitude;
NSLog(#"Halo");
theCoordinate.latitude = polyclinics1.latitude;
NSLog(#"bye");
//myAnnotation.pinColor = MKPinAnnotationColorPurple;
myAnnotation.coordinate = theCoordinate;
myAnnotation.title = polyclinics1.name;
myAnnotation.subtitle = [NSString stringWithFormat:#"%i",polyclinics1.telephone];
}
[_mapView addAnnotation:myAnnotation];
[_annotation2 addObject:myAnnotation];
}
Because you have different classes in your array you can't use for (PolyClinics *polyclinics1 in _listOfPolyClinics)to iterate over the array. Use idinstead, then ask the object of what class it is and then cast it to that class if you have to.
Try to change your second for loop to
for (id polyclinics1 in _listOfPolyClinics){
MyAnnotation* myAnnotation=[[MyAnnotation alloc] init];
if ([polyclinics1 isKindOfClass:[PatientDetails class]]){
CLLocationCoordinate2D theCoordinate3;
theCoordinate3.longitude = patientDetails.longitude;
theCoordinate3.latitude = patientDetails.latitude;
myAnnotation.coordinate = theCoordinate3;
myAnnotation.title = _nric;
myAnnotation.subtitle = [NSString stringWithFormat:#"%i",patientDetails.category];
} else {
CLLocationCoordinate2D theCoordinate;
PolyClinics *polyclinic = (PolyClinics *)polyclinics1;
theCoordinate.longitude = polyclinic.longtitude;
NSLog(#"Halo");
theCoordinate.latitude = polyclinic.latitude;
NSLog(#"bye");
//myAnnotation.pinColor = MKPinAnnotationColorPurple;
myAnnotation.coordinate = theCoordinate;
myAnnotation.title = polyclinic.name;
myAnnotation.subtitle = [NSString stringWithFormat:#"%i",polyclinic.telephone];
}
[_mapView addAnnotation:myAnnotation];
[_annotation2 addObject:myAnnotation];
}

NSString: fastes way of splitting

my question is a performance question.
I need to split a huge NSString into coordinates. The string has this format:
#"coordx,coordy coordx,coordy coordx,coordy (...)"
My method to parse this is:
-(NSMutableArray*) parsePath:(NSString*) pathString
{
// first split between the coordinates
NSArray* path = [pathString componentsSeparatedByString:#" "];
NSMutableArray* coords = [[NSMutableArray alloc] init];
static NSString *seperator = #",";
NSArray *coord;
for(NSString *coordString in path)
{
coord = [coordString componentsSeparatedByString:seperator];
Coordinate *c = [[Coordinate alloc]init];
c.x = [[coord objectAtIndex:0] intValue];
c.y = [[coord objectAtIndex:1] intValue];
[coords addObject:c];
[c release];
}
return coords;
}
So, is there any way to make this faster?
Thanks!
Sebastian
Using NSScanner is probably faster.
http://developer.apple.com/iphone/library/documentation/cocoa/reference/Foundation/Classes/NSScanner_Class/Reference/Reference.html