Back navigation issue using code - iphone

I am doing json parsing application. In which there is not an issue regarding parsing. I am having list uptill the type="0". But type="1" is having a description. All the "listing" as well as the "description" is set properly.
{"pageid":"5824","title":"Sms Collection","type":"0","desc":"Friendship SMS:$#|5825|#$:4cing.com/mobile_app/uploads/pageicon/friendship.png;Love SMS:$#|5826|#$:4cing.com/mobile_app/uploads/pageicon/Love.png;Miss U SMS:$#|5827|#$:4cing.com/mobile_app/uploads/pageicon/missu.png;Funny SMS:$#|5828|#$:4cing.com/mobile_app/uploads/pageicon/funny.png;Valentine SMS:$#|5829|#$:4cing.com/mobile_app/uploads/pageicon/valantine.png;Adult SMS:$#|5830|#$:4cing.com/mobile_app/uploads/pageicon/adult.png;Anniversary SMS:$#|5832|#$:4cing.com/mobile_app/uploads/pageicon/anniversary.png;Birthday SMS:$#|5833|#$:4cing.com/mobile_app/uploads/pageicon/birthday.png;Break up SMS:$#|5834|#$:4cing.com/mobile_app/uploads/pageicon/Breakup.png;Broken Heart SMS:$#|5835|#$:4cing.com/mobile_app/uploads/pageicon/heartbroken.png;Christmas SMS:$#|5836|#$:4cing.com/mobile_app/uploads/pageicon/Christmas.png;Exam SMS:$#|5837|#$:4cing.com/mobile_app/uploads/pageicon/exam.png;Flirt SMS:$#|5838|#$:4cing.com/mobile_app/uploads/pageicon/flirtsms.png;Good Luck SMS:$#|5839|#$:4cing.com/mobile_app/uploads/pageicon/goodluck.png;Good Morning SMS:$#|5840|#$:4cing.com/mobile_app/uploads/pageicon/goodmornig.png;Good Night SMS:$#|5841|#$:4cing.com/mobile_app/uploads/pageicon/goodnight.png;Insult SMS:$#|5842|#$:4cing.com/mobile_app/uploads/pageicon/inseart.png;Pashto SMS:$#|5843|#$:4cing.com/mobile_app/uploads/pageicon/pashto.png;Poetry SMS:$#|5844|#$:4cing.com/mobile_app/uploads/pageicon/poetry.png;Sardar SMS:$#|5845|#$:4cing.com/mobile_app/uploads/pageicon/sardar.png;Santa Banta SMS:$#|5846|#$:4cing.com/mobile_app/uploads/pageicon/santabanta.png;Smile SMS:$#|5847|#$:4cing.com/mobile_app/uploads/pageicon/smile.png;Sorry SMS:$#|5848|#$:4cing.com/mobile_app/uploads/pageicon/sorry.png;Chanakya SMS:$#|5849|#$:4cing.com/mobile_app/uploads/pageicon/chanakya.png;","cache":"1","Nexturl":"5825","prevurl":"0","bckurl":"0"}
when application is launched (type="0") this is the first list with above data.
Onclick of Friendship SMS cell i am getting (type="0") this data.
{"pageid":"5825","title":"Friendship SMS","type":"0","desc":"Do not lie, Do not cheat and do not make promises :$#|5850|#$:4cing.com/mobile_app/uploads/pageicon/friendship.png;There are no strings attached to a friendship, no :$#|5851|#$:4cing.com/mobile_app/uploads/pageicon/friendship.png;friends are like stars. You ca not always see them:$#|5852|#$:4cing.com/mobile_app/uploads/pageicon/friendship.png;Friends should b like zero. when u add, they r sam:$#|5853|#$:4cing.com/mobile_app/uploads/pageicon/friendship.png;Friendship is like a glass handle it with care bec:$#|5854|#$:4cing.com/mobile_app/uploads/pageicon/friendship.png;A friend gives hope when life is low, a friend is :$#|5855|#$:4cing.com/mobile_app/uploads/pageicon/friendship.png;How long shall we be friends? Do you want a clue? :$#|5856|#$:4cing.com/mobile_app/uploads/pageicon/friendship.png;My friendship is nothing but a round, Wandering wh:$#|5857|#$:4cing.com/mobile_app/uploads/pageicon/friendship.png;When nails are growing, We cut our nails, Not fing:$#|5858|#$:4cing.com/mobile_app/uploads/pageicon/friendship.png;A true friend understands when u say I forgot, wai:$#|5859|#$:4cing.com/mobile_app/uploads/pageicon/friendship.png;Making a million friends is not an achievement, Th:$#|5860|#$:4cing.com/mobile_app/uploads/pageicon/friendship.png;Friendship and Medicine both r good 4 our health:$#|5861|#$:4cing.com/mobile_app/uploads/pageicon/friendship.png;A memory lasts forever, and never does it die. Tru:$#|5862|#$:4cing.com/mobile_app/uploads/pageicon/friendship.png;Where there is no compromise in telling the secret:$#|5863|#$:4cing.com/mobile_app/uploads/pageicon/friendship.png;I m not Wealthy but i have Rich Heart, I m not Bes:$#|5864|#$:4cing.com/mobile_app/uploads/pageicon/friendship.png;Do not Love a Friend who Hurts U Do not Hurt a Fri:$#|5865|#$:4cing.com/mobile_app/uploads/pageicon/friendship.png;To hear what is unspoken, to see what is invisible:$#|5866|#$:4cing.com/mobile_app/uploads/pageicon/friendship.png;Life is 5 star Mother is top star Father is king s:$#|5867|#$:4cing.com/mobile_app/uploads/pageicon/friendship.png;A single rose can be my garden A single friend, my:$#|5868|#$:4cing.com/mobile_app/uploads/pageicon/friendship.png;To live a life i need heartbeat, 2 have heartbeat :$#|5869|#$:4cing.com/mobile_app/uploads/pageicon/friendship.png;A true relationship is when you can tell each othe:$#|5870|#$:4cing.com/mobile_app/uploads/pageicon/friendship.png;Friends\" are like balloons once u let them go u ca:$#|5871|#$:4cing.com/mobile_app/uploads/pageicon/friendship.png;MY friendship is just like a rubber band, It is to:$#|5872|#$:4cing.com/mobile_app/uploads/pageicon/friendship.png;I wish every relationship come with the same tag a:$#|5873|#$:4cing.com/mobile_app/uploads/pageicon/friendship.png;As precious as u r to me, As precious no one can e:$#|5874|#$:4cing.com/mobile_app/uploads/pageicon/friendship.png;Friendship Must Never Be Buried Under The Weight O:$#|5875|#$:4cing.com/mobile_app/uploads/pageicon/friendship.png;","cache":"1","Nexturl":"5850","prevurl":"5824","bckurl":"5849"}
Finally this is having (type="1") for the screen onclick of "Do not lie,Do not che..."
So description is shown as
I am having problem in the back process, i have to use prevurl which is similar to the pageid of rhe previous page, for the back functionality
This is the code which i am doing for the back functionality,
-(IBAction)btnBackClicked:(id)sender
{
int Type;
NSMutableDictionary *tempDict1;
for(int i=0;i<[test.JsonPageList count];i++)
{
tempDict1 = [[NSMutableDictionary alloc]init];
tempDict1 = (NSMutableDictionary *)[test.JsonPageList objectAtIndex:i];
NSLog(#"pageid is.....%d",[[tempDict1 valueForKey:#"pageid"] intValue]);
if ([[tempDict1 valueForKey:#"pageid"] intValue])
{
Type = [[tempDict1 valueForKey:#"type"] intValue];
if (Type == 0)
{
NSArray *arr=[[tempDict1 valueForKey:#"desc"] componentsSeparatedByString:#";"];
NSString *subStar = #"|#$:";
NSString *sub=#":$#|";
[test.arrTitle removeAllObjects];
[test.arrnew removeAllObjects];
[test.arrId removeAllObjects];
[test.arrImages removeAllObjects];
for (int i=0; i<[arr count]-1; i++)
{
[test.arrTitle addObject:[[arr objectAtIndex:i] substringToIndex:NSMaxRange([[arr objectAtIndex:i] rangeOfString:sub])-4]];
[test.arrnew addObject:[[arr objectAtIndex:i] substringFromIndex:NSMaxRange([[arr objectAtIndex:i] rangeOfString:sub])]];
[test.arrId addObject:[[test.arrnew objectAtIndex:i] substringToIndex:NSMaxRange([[test.arrnew objectAtIndex:i] rangeOfString:subStar])-4]];
[test.arrImages addObject:[[arr objectAtIndex:i] substringFromIndex:NSMaxRange([[arr objectAtIndex:i] rangeOfString:subStar])]];
}
[tbl_withData reloadData];
}
}
}
}
This is the code for the parsing
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
if ([[NSUserDefaults standardUserDefaults] boolForKey:#"SecondTime"])
{
[self saveData:responseData toFile:#"SMSCollection.txt"];
results = [responseString JSONValue];
JsonPageList = [results objectForKey:#"page"];
desc = [[NSMutableArray alloc] init];
for (NSString * strName in results)
{
JsonPageList = [results objectForKey:strName];
dictHash = [[NSMutableDictionary alloc] init];
[dictHash setObject:JsonPageList forKey:#"JsonPageList"];
for (int i = 0; i < [JsonPageList count]; i++)
{
[desc addObject:[[JsonPageList objectAtIndex:i] valueForKey:TAG_DESC]];
int PAGEID = [[NSString stringWithFormat:#"%#",[[JsonPageList objectAtIndex:i] valueForKey:#"pageid"]] intValue];
[self displayPage:PAGEID];
}
}
}
[responseString release];
}
-(void) displayPage:(int)pageID
{
page.pageid = pageID;
if (page.type == PAGE_TYPE_MENU)
{
NSString *desc1=[desc objectAtIndex:0];
NSArray *arr=[desc1 componentsSeparatedByString:#";"];
NSString *subStar = #"|#$:";
NSString *sub=#":$#|";
arrTitle=[[NSMutableArray alloc] init];
arrImages = [[NSMutableArray alloc] init];
arrnew = [[NSMutableArray alloc]init];
arrId=[[NSMutableArray alloc]init];
for (int i=0; i<[arr count]-1; i++)
{
[arrTitle addObject:[[arr objectAtIndex:i] substringToIndex:NSMaxRange([[arr objectAtIndex:i] rangeOfString:sub])-4]];
[arrnew addObject:[[arr objectAtIndex:i] substringFromIndex:NSMaxRange([[arr objectAtIndex:i] rangeOfString:sub])]];
[arrId addObject:[[arrnew objectAtIndex:i] substringToIndex:NSMaxRange([[arrnew objectAtIndex:i] rangeOfString:subStar])-4]];
[arrImages addObject:[[arr objectAtIndex:i] substringFromIndex:NSMaxRange([[arr objectAtIndex:i] rangeOfString:subStar])]];
}
}
else if (page.type == PAGE_TYPE_CONTENT)
{
NSLog(#"CURR title:- %#\n & desc:- %#",page.title1 ,page.desc);
UITextView *TextView = [[UITextView alloc] init];
TextView.text = page.title1;
UILabel *lblcurrentPage = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 300)];
lblcurrentPage.backgroundColor = [UIColor whiteColor];
lblcurrentPage.textColor = [UIColor blackColor];
lblcurrentPage.text = page.desc;
}
}
Help me out of this problem.

Related

Getting the wrong sorted distance on the basis of lat and long

I am getting very strange issues in my app,there is a section where i am collecting the data from the server, in response i am getting the lat and long for all the near by restaurants,by using these lat and long i am getting the distances of each from the current user location,and i have applied the sorting like closet to further from the current user location on the collected data,everthing works fine at my end but whenever client test this at his end then the sorting doesn't work.I have attached the code for this here.
- (void)viewDidLoad
{
[super viewDidLoad];
myDelegate= (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSLog(#"Lat %f", [[myDelegate.myLocation objectForKey:#"LATITUDE"]floatValue]);
NSLog(#"Long %f",[[myDelegate.myLocation objectForKey:#"LONGITUDE"]floatValue]);
self.coordArray= [[NSMutableArray alloc]init];
// Do any additional setup after loading the view from its nib.
timer=[NSTimer scheduledTimerWithTimeInterval:(10.0) target:self selector:#selector(upateLocation) userInfo:nil repeats:YES];
float dist;
for (int i=0; i<[myDelegate.placeArray count]; i++) {
dist=(6371 * acos(cos(RADIANS_TO_DEGREES([[myDelegate.myLocation objectForKey:#"LATITUDE"]floatValue]) ) *
cos(RADIANS_TO_DEGREES([[[myDelegate.placeArray objectAtIndex:i] latitude] floatValue] ) ) * cos( RADIANS_TO_DEGREES([[[myDelegate.placeArray objectAtIndex:i] longitude] floatValue] ) - RADIANS_TO_DEGREES([[myDelegate.myLocation objectForKey:#"LONGITUDE"]floatValue]) ) + sin( RADIANS_TO_DEGREES([[myDelegate.myLocation objectForKey:#"LATITUDE"]floatValue])) * sin( RADIANS_TO_DEGREES([[[myDelegate.placeArray objectAtIndex:i] latitude] floatValue] ) ) ) );
//int distVal=(int)dist;
distStr= [NSString stringWithFormat:#"%.2f",dist];
NSLog(#"new---%#",distStr);
[self.coordArray addObject:distStr];
}
NSMutableDictionary *tmpDict;
for (int i=0; i<[myDelegate.placeArray count]; i++) {
tmpDict = [[NSMutableDictionary alloc]initWithObjectsAndKeys:[[myDelegate.placeArray objectAtIndex:i] ids],#"contentId",[[myDelegate.placeArray objectAtIndex:i] restaurantname],#"contentTitle",//contentAdd
[[myDelegate.placeArray objectAtIndex:i] res_type],#"contentType",
[[myDelegate.placeArray objectAtIndex:i] user_image],#"contentImg",[[myDelegate.placeArray objectAtIndex:i] address],#"contentAdd",[[myDelegate.placeArray objectAtIndex:i] phone],#"contentPhone",
[self.coordArray objectAtIndex:i],#"contentDist",nil];
[self.dataArray addObject:tmpDict];
[tmpDict release];
tmpDict = nil;
// NSLog(#"self.dataArray---%f",[[[self.dataArray objectAtIndex:i] valueForKey:#"contentDist"] floatValue]);
}
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
[tempArray removeAllObjects];
[tempArray addObjectsFromArray: self.dataArray];
NSString *key = #"contentDist";
NSSortDescriptor *brandDescriptor = [[NSSortDescriptor alloc] initWithKey:key ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObjects:brandDescriptor,nil];
NSArray *sortedArray = [tempArray sortedArrayUsingDescriptors:sortDescriptors];
[brandDescriptor release];
[tempArray removeAllObjects];
tempArray = (NSMutableArray*)sortedArray;
[self.dataArray removeAllObjects];
[self.dataArray addObjectsFromArray:tempArray];
/*haversine=[[Haversine alloc] init];
[haversine initWithLat1:28.618095 lon1:77.390228 lat2:28.635860 lon2:77.506226];
[haversine toKilometers];
NSLog(#"haversine--- %f",[haversine toKilometers]);*/
// [self performSelector:#selector(upateLocation) withObject:nil afterDelay:10.0];
}
}
Here is the explanation of the above code.
1-Have an Array (place Array) which having all lat and long corresponding to each restaurants.
2-From this array,by using Harvest method i am getting the distances in km and then adding these into another array named (coordArray).
3-Then Creating a final array i.e (dataArray on which i have applied the sorting
This works fine at my end but doesn't work once i tested on iPhone 5.
Can anyone suggest me what is wrong with this code which i am not geting.
Please help me out from this and thanks to all for giving your precious time .
Not really an answer but I believe you can reformat your code to remove lots of unnecessary looping. Just made the code similar to yours you can store the distance as NSNumber. You can also use fast enumeration to remove lots of verbosity.
self.dataArray = [NSMutableArray array];
for (int i=0; i<[myDelegate.placeArray count]; i++) {
float dist=(6371 * acos(cos(RADIANS_TO_DEGREES([[myDelegate.myLocation objectForKey:#"LATITUDE"]floatValue]) ) *
cos(RADIANS_TO_DEGREES([[[[myDelegate.placeArray objectAtIndex:i] latitude] floatValue] ) ) * cos( RADIANS_TO_DEGREES([[[myDelegate.placeArray objectAtIndex:i] longitude] floatValue] ) - RADIANS_TO_DEGREES([[myDelegate.myLocation objectForKey:#"LONGITUDE"]floatValue]) ) + sin( RADIANS_TO_DEGREES([[myDelegate.myLocation objectForKey:#"LATITUDE"]floatValue])) * sin( RADIANS_TO_DEGREES([[[myDelegate.placeArray objectAtIndex:i] latitude] floatValue] ) ) ) );
//int distVal=(int)dist;
NSString *distStr= [NSString stringWithFormat:#"%.2f",dist];
NSDictionary *tmpDict = #{#"contentId":[[myDelegate.placeArray objectAtIndex:i] ids],
#"contentTitle":[[myDelegate.placeArray objectAtIndex:i] restaurantname],
#"contentType":[[myDelegate.placeArray objectAtIndex:i] res_type],
#"contentImg":[[myDelegate.placeArray objectAtIndex:i] user_image],
#"contentAdd":[[myDelegate.placeArray objectAtIndex:i] address],
#"contentPhone":[[myDelegate.placeArray objectAtIndex:i] phone],
#"contentDist":distStr};
[self.dataArray:tmpDict];
}
NSSortDescriptor *brandDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"contentDist"
ascending:YES];
[self.dataArray sortUsingDescriptors:#[brandDescriptor]];
If you store the distances as strings:
distStr= [NSString stringWithFormat:#"%.2f",dist];
NSLog(#"new---%#",distStr);
[self.coordArray addObject:distStr];
then they will be sorted as strings and not as numbers, for example 11.00 < 2.00.
You should store the distances as NSNumber objects instead:
[self.coordArray addObject:[NSNumber numberWithFloat:dist]];
(Note that CLLocation has a distanceFromLocation:
method that you could use instead of your own computation.)

iphone: addObjectsFromArray not adding after reinitializing nsmutable array

i have the following code
inAppKeys = [[MKStoreManager sharedManager] purchasableObjectsDescription ];
NSMutableArray * unremovableArray = [[NSMutableArray alloc] init];
for(int i = 0; i<[inAppKeys count]; i++){
for (int j=0; j< [categories count]; j++) {
NSString * inAppKey = [[categories objectAtIndex:j] valueForKey:#"inAppKey"];
if([inAppKey isEqualToString: [inAppKeys objectAtIndex:i]]){
[unremovableArray addObject:[categories objectAtIndex:j]];
}
}
}
categories = [[NSMutableArray alloc] init];
[categories addObjectsFromArray:unremovableArray];
where categories is nsmutablearray .. the thing is addObjectsFromArray leave the categories empty .. what do i do wrong?
Looks to me like you're referring to [categories count] and [categories objectAtIndex:j] before you even alloc/init categories.
Having re-read your title ("reinitializing") which suggests you've previously inited categories, I'm now assuming that you have a master set of categories that you're trying to reduce to the ones actually purchased. If so, I wouldn't re-use the variable "categories" as that's confusing. (I assume categories was auto-released, or else you've got a leak). How 'bout using unremovableArray instead of leaking it?
I'd also use fast enumerators for clarity and speed...
NSLog(#"categories: %#", categories);
inAppKeys = [[MKStoreManager sharedManager] purchasableObjectsDescription ];
NSLog(#"inAppKeys:%#", inAppKeys);
NSMutableArray * unremovableCategories = [[NSMutableArray alloc] init];
for(NSString* thisAppKey in inAppKeys) {
for (NSDictionary* thisCategory in categories) {
if ([[thisCategory valueForKey:#"inAppKey"] isEqualToString: thisAppKey]){
[unremovableCategories addObject:thisCategory];
break; //having added this category; no reason to continue looking at it
}
}
}
//now use unremovableCategories...

how to create an C Array

his guys,
i think this is a simple question but i do not know how to do it.
how do i create the line below dynamically from an array?
this is what i need to call.
//data source
NSString * sourceData[7] = {#"2", #"1", #"4", #"8", #"14", #"15", #"10"};
chartData = [WSData dataWithValues:[WSData arrayWithString:sourceData withLen:7]];
+ (NSArray *)arrayWithString:(NSString *[])strings
withLen:(NSUInteger)len {
NSMutableArray *tmpArr = [NSMutableArray
arrayWithCapacity:len];
NSUInteger i;
for (i=0; i<len; i++) {
[tmpArr addObject:strings[i]];
}
return [NSArray arrayWithArray:tmpArr];
}
thanks for all the help especially Daniel :)
this is the answer to the question
NSMutableArray * dayArray = [[NSMutableArray alloc] init];
dayArray = [NSMutableArray arrayWithCapacity:7];
NSMutableArray * sdArray = [[NSMutableArray alloc] init];
sdArray = [NSMutableArray arrayWithCapacity:7];
NSInteger drunked = [appDelegate.drinksOnDayArray count];
if (drunked !=0)
{
for(int i=6; i>=0; i--)
{
DayOfDrinks *drinksOnDay = [appDelegate.drinksOnDayArray objectAtIndex:i];
NSString * dayString= [NSDate stringForDisplayFromDateForChart:drinksOnDay.dateConsumed];
[dayArray addObject:dayString];//X label for graph the day of drink.
drinksOnDay.isDetailViewHydrated = NO;
[drinksOnDay hydrateDetailViewData];
NSNumber *sdNumber = drinksOnDay.standardDrinks;
[sdArray addObject: sdNumber];
}
NSString *sData[7];// = malloc(7 * sizeof(NSString *));
for (int i=0; i<7; i++)
{
DayOfDrinks *drinksOnDay = [appDelegate.drinksOnDayArray objectAtIndex:i];
sData[i] = [NSString stringWithFormat:#"%#",drinksOnDay.standardDrinks];
}
NSString * sourceData[7] = {sData[6],sData[5],sData[4],sData[3],sData[2],sData[1],sData[0] };
}
If you are only using the array as a call parm, and are not storing it somewhere or returning it from your current method:
NSString* sourceData[7];
for (i = 0; i < 7; i++) {
int num = <getTheValueYouWant>;
sourceData[i] = [NSString stringWithFormat:#"%d", num];
}
But note that if you intend to return the array, or store it in some long-lived variable, you need an entirely different setup.
So this is how you would create an NSMutableArray. Mutable because you're creating it at runtime.
NSString * sourceData = [[NSString alloc] initWithFormat:#""];
//assuming the array you have is arr with NSNumber objects
for (NSNumber *num in arr) {
[sourceData stringByAppendingFormat:#"%#", num];
}
You can try below code with the loop as you required.....
NSMutableArray *array;
array = [[NSMutableArray alloc] init];
[array addObject:[NSNumber numberWithFloat:1.0f]];
[array release];

Creating a long NSString causing memory issues

My code below is causing my app to quit i.e. get black screen and then see in debugger console: Program received signal: “0”.
Basically it is causing problem when my orderArray has count of 2000 or more. I am using iPhone 3GS with iOS 4.2
Question: Is there a more efficient and less memory consuming way to create my long outStr?
NSString *outStr = #"";
for (int i = 0; i < count; i++) {
NSDictionary *dict = [[ARAppDelegate sharedAppDelegate].orderArray objectAtIndex:i];
outStr = [outStr stringByAppendingFormat:#"%#,%#,%#,%#\n",
[dict valueForKey:#"CODE"],
[dict valueForKey:#"QTY"],
[[ARAppDelegate sharedAppDelegate].descDict valueForKey:[dict valueForKey:#"CODE"]],
[[ARAppDelegate sharedAppDelegate].priceDict valueForKey:[dict valueForKey:#"CODE"]]];
}
Update: Thanks to very kind people who helped, below is my modified code:
NSArray *orderA = [ARAppDelegate sharedAppDelegate].orderArray;
NSDictionary *descD = [ARAppDelegate sharedAppDelegate].descDict;
NSDictionary *priceD = [ARAppDelegate sharedAppDelegate].priceDict;
NSMutableString *outStr = [[[NSMutableString alloc] init] autorelease];
for (int i = 0; i < [orderA count]; i++) {
NSDictionary *dict = [orderA objectAtIndex:i];
NSString *code = [dict valueForKey:#"CODE"];
[outStr appendFormat:#"%#,%#,%#,%#\n",
code,
[dict valueForKey:#"QTY"],
[descD valueForKey:code],
[priceD valueForKey:code]];
}
[self emailTxtFile:[NSString stringWithString:outStr]];
// This reaches end of method
The problem is that in every iteration a new string object is formed. This consumes a lot of memory. One solution could be to use a local autoreleasepool, but that's rather complicated here.
You should use an NSMutableString, like:
NSMutableString *outStr = [[[NSMutableString alloc] init] autorelease];
for (int i = 0; i < count; i++) {
NSDictionary *dict = [[ARAppDelegate sharedAppDelegate].orderArray objectAtIndex:i];
[outStr appendFormat:#"%#,%#,%#,%#\n",
[dict valueForKey:#"CODE"],
[dict valueForKey:#"QTY"],
[[ARAppDelegate sharedAppDelegate].descDict valueForKey:[dict valueForKey:#"CODE"]],
[[ARAppDelegate sharedAppDelegate].priceDict valueForKey:[dict valueForKey:#"CODE"]]];
}
Then you can use outStr, just as if it was an NSString. As Tom points out in the comments, you could turn the NSMutableString into an NSString when you're finished, using:
NSString *result = [NSString stringWithString:outStr];
[outStr release]; // <-- add this line and remove the autorelease
// from the outStr alloc/init line
making your code re-usable and easier to maintain.

Converting table view to have sections

I have a table view, which has its data source from an array that contains names of people.
Now to make it easy to find people, I want to section the table view so that it has the letter A-Z on the right hand side, just like the Address Book app.
But my current array just contains a collection of NSStrings. How do I split them so that they are grouped by the first letter of the names? Is there any convenient way to do it?
EDIT: If anyone's interested in my final code:
NSMutableArray *arrayChars = [[NSMutableArray alloc] init];
for (char i = 'A'; i <= 'Z' ; i++) {
NSMutableDictionary *characterDict = [[NSMutableDictionary alloc]init];
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
for (int k = 0; k < [myList count]; k++) {
NSString *currentName = [[friends objectAtIndex:k] objectForKey:#"name"];
char heading = [currentName characterAtIndex:0];
heading = toupper(heading);
if (heading == i) {
[tempArray addObject:[friends objectAtIndex:k]];
}
}
[characterDict setObject:tempArray forKey:#"rowValues"];
[characterDict setObject:[NSString stringWithFormat:#"%c",i] forKey:#"headerTitle"];
[arrayChars addObject:characterDict];
[characterDict release];
[tempArray release];
}
At the end of the function I'll have:
arrayChars [0] = dictionary(headerTitle = 'A', rowValues = {"adam", "alice", etc})
arrayChars[1] = dictionary(headerTitle = 'B', rowValues = {"Bob", etc})
Thank you everyone for your help!
You can use a dictionary to sort them, so create an array with all the letters you want to sort and a array with nil objects to initialize the dictionary
NSArray *names = #[#"javier",#"juan", #"pedro", #"juan", #"diego"];
NSArray *letters = #[#"j", #"p", #"d"];
NSMutableArray *objects = [[NSMutableArray alloc] init];
for (NSInteger i = 0; i < [letters count]; ++i)
{
[objects addObject:[[NSMutableArray alloc] init]];
}
NSDictionary *dictionary = [[NSDictionary alloc] initWithObjects:objects forKeys:letters];
Then you must find the first letter if the word and put that word into the corresponding key in the dictionary
for (NSString *name in names) {
NSString *firstLetter = [name substringToIndex:1];
for (NSString *letter in letters) {
if ([firstLetter isEqualToString:letter]) {
NSMutableArray *currentObjects = [dictionary objectForKey:letter];
[currentObjects addObject:name];
}
}
}
To check you can print directly the dictionary
NSLog(#"%#", dictionary);
Then is your work to fill your sections in the tableview using the dictionary