Memory management in appending a string? - iphone

I have an iPhone application in which i am creating an array in the didfinishlaunch in the appdelegate. Like this:
for(int i=1;i<53;i++)
{
NSString *namestring=[NSString stringWithString:#"avatar"];
NSString *string = [NSString stringWithFormat:#"%d",i];
NSString *pngstring=[NSString stringWithString:#".png"];
string = [string stringByAppendingString:pngstring];
namestring = [namestring stringByAppendingString:string];
NSLog(#"%#",namestring);
[avtararray addObject:namestring];
}
working fine.and everywhere i am doing the avatar job with my avatararray in the appdelegate.But in one case when i pop back to the previous view and try to load the string from the array again
NSString *avatarstringt=[[appDelegate.avtararray objectAtIndex:i]description];here it is crashing with a an error
-[CFString description]: message sent to deallocated instance..
when doing the profile job i know that the leak is in the above loop in the appendingstring code.Can anybody help me to remove this?

First of all, Never do this
NSString *string = [NSString stringWithFormat:#"%d",i];
NSString *pngstring=[NSString stringWithString:#".png"];
string = [string stringByAppendingString:pngstring];
The following statements, are redundant
NSString *namestring=[NSString stringWithString:#"avatar"];
NSString *pngstring=[NSString stringWithString:#".png"];
and should be written as:
NSString *namestring=#"avatar";
NSString *pngstring=#".png";
You can use as :
NSString *namestring=#"avatar";
NSString *numberString = [NSString stringWithFormat:#"%d",i];
NSString *pngstring=#"png";
namestring = [namestring stringByAppendingFormat:#"%#.%#",numberString,pngstring];
Even the shortest of code :
for(NSInteger i=1;i<5;i++){
NSString *namestring = [NSString stringWithFormat:#"avatar%#.png",#(i)];
NSLog(#"%#",namestring);
}
As suggested by rmaddy: you can use i as integer, no need of converting it into nsnumber
NSString *namestring = [NSString stringWithFormat:#"avatar%d.png",i];

Related

how to give space between two string while concatnating

I am concatenating two string using following way I want space between Added Content To My Learning And the second String any idea how to give space thanks
NSString *firstString =#"Added Contnet To My Learning";
NSString *secondString = appDelegate.activity_Description;
appDelegate.activity_Description = [firstString stringByAppendingString:secondString];
You can do it like this.
NSString *firstString =#"Added Contnet To My Learning";
NSString *secondString = appDelegate.activity_Description;
appDelegate.activity_Description = [NSString stringWithFormat:#"%# %#", firstString, secondString];
Did you try?
NSString *firstString =#"Added Contnet To My Learning ";
// a space after the first string
Here is all way you can do with string
//1st Way
NSString *finalString = [NSString stringWithFormat:#"%# %#",firstString,secondString];
//2nd Way
NSString *finalString = [firstString stringByAppendingFormat:#" %#",secondString];
//3rd way
NSArray *ary= [NSArray arrayWithObjects:firstString,secondString, nil];
NSString *finalString= [ary componentsJoinedByString:#" "];
Follow this how to concatenate two strings in iphone

Convert String into special - splitting an NSString

I have a string like: "mocktail, wine, beer"
How can I convert this into: "mocktail", "wine", "beer"?
the following gives you the desired result:
NSString *_inputString = #"\"mocktail, wine, beer\"";
NSLog(#"input string : %#", _inputString);
NSLog(#"output string : %#", [_inputString stringByReplacingOccurrencesOfString:#", " withString:#"\", \""]);
the result is:
input string : "mocktail, wine, beer"
output string : "mocktail", "wine", "beer"
You need to use:
NSArray * components = [myString componentsSeparatedByString: #", "];
NSString *string = #"mocktail, wine, beer";
//remove whitespaces
NSString *trimmedString = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//get array of string
NSArray *array = [trimmedString componentsSeparatedByString:#","];
NSMutableArray *newArray = [[NSMutableArray alloc] init];
for (NSString *trimmedString in array) {
NSString *newString = [NSMutableString stringWithFormat:#"'%#'", trimmedString];
[newArray addObject:newString];
}
//merge new strings
NSString *finalString = [NSString stringWithFormat:#"%#", [newArray objectAtIndex:0]];
for (NSInteger i = 1; i < [newArray count]; i++) {
finalString = [NSString stringWithFormat:#"%#, %#", finalString, [newArray objectAtIndex:i]];
}
Without knowing spesifically about iOS or objective-c, I assume you could use a split function.
In almost any higher level programming language there is such a function.
Try:
Objective-C split
This gets you an array of Strings. You can then practically do with those what you want to do, e.g. surrounding them with single quotes and appending them back together. :D

NSRegularExpression to extract text

All,
I have a dictionary with two keys and values. I need to extract bits and pieces from them and place them into seperate strings.
{
IP = "192.168.17.1";
desc = "VUWI-VUWI-ABC_Dry_Cleaning-R12-01";
}
That is what the dictionary looks like when I call description.
I want the new output to be like this:
NSString *IP = #"192.168.17.1";
NSString *desc = #"ABC Dry Cleaning"; //note: I need to get rid of the underscores
NSString *type = #"R";
NSString *num = #"12";
NSString *ident = #"01";
How would I achieve this?
I've read through the Apple developer docs on NSRegularExpression but I find it hard to understand. I'm sure once I get some help once here I can figure it out in the future, I just need to get started.
Thanks in advance.
Okay, so first, you have to get the object associated with each key:
NSString *ip = [dic objectForKey:#"IP"]; //Btw, you shouldn't start a variable's name with a capital letter.
NSString *tempDesc = [dic objectForKey:#"desc"];
Then, what I would do is split the string in tempDesc, based on the character -.
NSArray *tmpArray = [tempDesc componentsSeparatedByString:#"-"];
Then you just have to get the strings or substrings you're interested in, and reformat them as needed:
NSString *desc = [[tmpArray objectAtIndex:2] stringByReplacingOccurrencesOfString:#"_" withString:#" "];
NSString *type = [[tmpArray objectAtIndex:3] substringToIndex:1];
NSString *num = [[tmpArray objectAtIndex:3] substringFromIndex:1];
NSString *ident = [tmpArray objectAtIndex:4];
As you can see, this works perfectly without using NSRegularExpression.

Get last path part from NSString

Hi all i want extract the last part from string which is a four digit number '03276' i:e http://www.abc.com/news/read/welcome-new-gig/03276
how can i do that.
You can also use
NSString *sub = [#"http://www.abc.com/news/read/welcome-new-gig/03276" lastPathComponent];
If you know how many characters you need, you can do something like this:
NSString *string = #"http://www.abc.com/news/read/welcome-new-gig/03276";
NSString *subString = [string substringFromIndex:[string length] - 5];
If you just know that it's the part after the last slash, you can do this:
NSString *string = #"http://www.abc.com/news/read/welcome-new-gig/03276";
NSString *subString = [[string componentsSeparatedByString:#"/"] lastObject];
Since *nix uses the same path separators as URL's this will be valid as well.
[#"http://www.abc.com/news/read/welcome-new-gig/03276" lastPathComponent]
If you know the length of the number, and it's not gonna change, it can be as easy as:
NSString *result = [string substringFromIndex:[string length] - 4];
If the last part of the string is always the same length (5 characters) you could use this method to extract the last part:
- (NSString *)substringFromIndex:(NSUInteger)anIndex
Use the length of the string to determine the start index.
Something like this:
NSString *inputStr = #"http://www.abc.com/news/read/welcome-new-gig/03276";
NSString *newStr = [inputStr substringFromIndex:[inputStr length]-5];
NSLog(#"These are the last five characters of the string: %#", newStr);
(Code not tested)
NSString *str = #"http://www.abc.com/news/read/welcome-new-gig/03276";
NSArray *arr = [str componentSeparatedBy:#"gig/"];
NSString *strSubStringDigNum = [arr objectAtIndex:1];
strSubStringDigNum will have the value 03276
Try this:
NSString *myUrl = #"http://www.abc.com/news/read/welcome-new-gig/03276";
NSString *number = [[myUrl componentsSeparatedByString:#"/"] objectAtIndex: 5];

obj-c problem setting array with componentsSeperatedByString

I have a data source with about 2000 lines that look like the following:
6712,Anaktuvuk Pass Airport,Anaktuvuk Pass,United States,AKP,PAKP,68.1336,-151.743,2103,-9,A
What I am interested in is the 6th section of this string so I want to turn it into an array, then i want to check the 6th section [5] for an occurrance of that string "PAKP"
Code:
NSBundle *bundle = [NSBundle mainBundle];
NSString *airportsPath = [bundle pathForResource:#"airports" ofType:#"dat"];
NSData *data = [NSData dataWithContentsOfFile:airportsPath];
NSString *dataString = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
NSArray *dataArray = [dataString componentsSeparatedByString:#"\n"];
NSRange locationOfAirport;
NSString *workingString = [[NSString alloc]initWithFormat:#""];
NSString *searchedAirport = [[NSString alloc]initWithFormat:#""];
NSString *airportData = [[NSString alloc]initWithFormat:#""];
int d;
for (d=0; d < [dataArray count]; d=d+1) {
workingString = [dataArray objectAtIndex:d];
testTextBox = workingString; //works correctly
NSArray *workingArray = [workingString componentsSeparatedByString:#","];
testTextBox2 = [workingArray objectAtIndex: 0]; //correctly displays the first section "6712"
testTextBox3 = [workingArray objectAtIndex:1] //throws exception index beyond bounds
locationOfAirport = [[workingArray objectAtIndex:5] rangeOfString:#"PAKP"];
}
the problem is that when the workingArray populates, it only populates with a single object (the first component of the string which is "6712". If i have it display the workingString, it correctly displays the entire string, but for some reason, it isn't correctly making the array using the commas.
i tried it without using the data file and it worked fine, so the problem comes from how I am importing the data.
ideas?
You code works. You should run it with the debugger to see what's happening. At a guess, your input data isn't what you think it is - possibly a different encoding, or different line endings.
See sample:
NSString *dataString = #"6712,Anaktuvuk Pass Airport,Anaktuvuk Pass,United States,AKP,PAKP,68.1336,-151.743,2103,-9,A";
NSArray *dataArray = [dataString componentsSeparatedByString:#"\n"];
for (NSString *workingString in dataArray) {
NSString *testTextBox = workingString; //works correctly
NSArray *workingArray = [workingString componentsSeparatedByString:#","];
NSString *testTextBox2 = [workingArray objectAtIndex: 0]; //correctly displays the first section "6712"
NSString *testTextBox3 = [workingArray objectAtIndex:1]; //throws exception index beyond bounds
NSRange locationOfAirport = [[workingArray objectAtIndex:5] rangeOfString:#"PAKP"];
}
there was a problem in the data where there were a few "\"s that caused the errors.