iOS: changing NSString value - ios

Will this bit of code produce any memory leaks? Is it the correct way to change NSString values?
NSString * enemiesAndElementsTextureFileName = #"bla bla";
enemiesAndElementsTextureFileName = #"bl";

That way of doing it won't cause any memory leaks and it is indeed correct. In this case you wouldn't need an NSMutableString because you aren't altering the string literal itself, you are simply replacing the string value with a new one (replacing #"bla bla" with #"bl").
In this case, however, your string will now be 'bl', so you can delete that first line value and just have NSString * enemiesAndElementsTextureFileName = #"bl";

Yes NSString allocated once. This is one of the way

Yes, use NSMutableString with the following method as your needs:
// Allocate
NSMutableString *str = [[NSMutableString alloc] initWithCapacity:10];
// set string content
[str setString:#"1234"];
// Append
[str appendString:#"567"];
// Concat
[str appendFormat:#"age is %i and height is %.2f", 27, 1.55f];
// Replace
NSRange range = [str rangeOfString:#"height"];//查找字符串height的位置
[str replaceCharactersInRange:range withString:#"no"];
// Insert
[str insertString:#"abc" atIndex:2];
// Delete
range = [str rangeOfString:#"age"];
[str deleteCharactersInRange:range];
NSLog(#"%#", str);

Related

present NSString as a line of elements

I have an NSString that hold data (actually that could be presented an NSArray). and i want to output that on a label.
In NSLog my NSString output is:
(
"cristian_camino",
"daddu_02",
"_ukendt_babe_",
"imurtaza.zoeb"
)
What i want is, to present it like :"cristian_camino","daddu_02","_ukendt_babe_","imurtaza.zoeb"
In a single line.
I could accomplish that turning string to an array and do following: arrayObjectAtIndex.0, arrayObjectAtIndex.1, arrayObjectAtIndex.2, arrayObjectAtIndex.3.
But thats look not good, and that objects may be nil, so i prefer NSString to hold data.
So, how could i write it in a single lane?
UPDATE:
There is the method i want to use to set text for UILabel:
-(void)setLikeLabelText:(UILabel*)label{
//Likes
NSString* likersCount = [self.photosDictionary valueForKeyPath:#"likes.count"];
NSString* likersRecent = [self.photosDictionary valueForKeyPath:#"likes.data.username"];
NSString *textString = [NSString stringWithFormat:#"%# - amount of people like it, recent "likes": %#", likersCount, likersRecent];
label.text = textString;
NSLog(#"text String is %#", textString);
}
valueForKeyPath: returns an NSArray, not an NSString. Whilst you've declared likersCount and likersRecent as instances of NSString, they're actually both arrays of values. You should be able to do something like the following to construct a string:
NSArray* likersRecent = [self.photosDictionary valueForKeyPath:#"likes.data.username"];
NSString *joined = [likersRecent componentsJoinedByString:#"\", \""];
NSString *result = [NSString stringWithFormat:#"\"%#\"", joined];
NSLog(#"Result: %#", result);
componentsJoinedByString: will join the elements of the array with ", ", and then the stringWithFormat call will add a " at the beginning and end.
The statement is incorrect, the internal quote marks (" that you want to display) need to be escaped:
NSString *textString = [NSString stringWithFormat:#"%# - amount of people like it, recent \"likes\": %#", likersCount, likersRecent];
If somebody curious how i fix it, there it is:
for (int i =0; i < [likersRecent count]; i++){
stringOfLikers = [stringOfLikers stringByAppendingString:[NSString stringWithFormat:#" %#", [likersRecent objectAtIndex:i]]];
}
Not using commas or dots though.

In objective-c how to get characters after n-th?

I have a number which will be represented as string. It is longer than 4 chars. I need to create new string from 5th till the end for that number.
For example if I have 56789623, I need to have 9623 as a result (5678 | 9623).
How to do that?
P.S. I suppose that this is very simple question, but I don't know how properly ask Google about that.
NSString *str = #"56789623";
NSString *first, *second;
if ([str length] > 4) {
first = [str substringWithRange:NSMakeRange(0, 4)];
second = [str substringWithRange:NSMakeRange(4, [str length] - 4)];
} else {
first = str;
second = nil;
}
Use this Simple functions
- (NSString *)substringFromIndex:(NSUInteger)from;
- (NSString *)substringToIndex:(NSUInteger)to;
- (NSString *)substringWithRange:(NSRange)range;
You can use:
- (NSString *)substringFromIndex:(NSUInteger)anIndex
NSString *number = #"56789623";
NSString *result = [number substringFromIndex:4];
NSLog(#"%#", result);
result contains the string: #"9623"
The keywords you were looking for are: substring and range. There are several ways to use them. Example code split string into 2 equal (if number of characters is even almost equal) substrings:
NSString *str = #"56789623";
NSInteger middleIndex = (NSInteger)(str.length/2);
NSString *strFirstPart = [str substringToIndex:middleIndex];
NSString *strSecondPart = [str substringFromIndex:middleIndex];
NSString *strFirstPart2 = [str substringWithRange:NSMakeRange(0, middleIndex)];
NSString *strSecondPart2 = [str substringWithRange:NSMakeRange(middleIndex, [str length]-middleIndex)];

Getting Remaining Text After Selection is Cut

Is there a simple way of getting remaining text after selection is cut? Let me suppose that I have a textview control with "Hello, Jim" in it. If "Jim" is selected, I want to store "Hello" to a variable, " without using [textview1 cut:self]. In the following code, I can get the other part.
UITextRange *selectedTextRange = textview1.selectedTextRange;
NSUInteger location = [textview1 offsetFromPosition:textview1.beginningOfDocument toPosition:selectedTextRange.start];
NSUInteger length = [textview1 offsetFromPosition:selectedTextRange.start toPosition:selectedTextRange.end];
NSRange selectedRange = NSMakeRange(location, length);
NSString *str = [textview1.text substringWithRange:selectedRange];
NSLog(#"%#",str);
Of course, that's the other part.
Thank you for your help.
NSString *remaining = [textview1.text stringByReplacingCharactersInRange:textview1.selectedRange withString:#""];
I think it's something like the following. (Revised)
NSMutableString *str = [NSMutableString stringWithString:#""];
if (textview1.text.length > length) {
[str appendString:[textview1.text substringToIndex:location]];
[str appendString:[textview1.text substringFromIndex:location + length]];
} else {
[str appendString:#""];
}
[self setText:str];

How to right pad a string using stringWithFormat

I would like to be able to right align a string using spaces. I have to be able to use the stringWithFormat: method.
So far I have tried the recommended format and it does not seem to work: [NSString stringWithFormat:#"%10#",#"test"].
I would expect this to return a string that has six spaces followed by "test" but all I am getting is "test" with no spaces.
It appears that stringWithFormat ignores the sizing requests of the %# format specifier. However, %s specifier works correctly:
NSString *test = #"test";
NSString *str = [NSString stringWithFormat:#"%10s", [test cStringUsingEncoding:NSASCIIStringEncoding]];
NSLog(#"'%#'", str);
This prints ' test'.
It's C style formatting. %nd means the width is n.
check following code.
NSLog(#"%10#",[NSString stringWithFormat:#"%10#",#"test"]);
NSLog(#"%#",[NSString stringWithFormat:#" %#",#"test"]);
NSLog(#"%10#", #"test");
NSLog(#"%10s", [#"test" cStringUsingEncoding:[NSString defaultCStringEncoding]]);
NSLog(#"%10d", 1);
NSString *str = #"test";
int padding = 10-[str length]; //6
if (padding > 0)
{
NSString *pad = [[NSString string] stringByPaddingToLength:padding withString:#" " startingAtIndex:0];
str = [pad stringByAppendingString:str];
}
NSLog(#"%#", str);

Using substringFromIndex on NSMutableString

Why is substringFromIndex not working for my NSMutableString ?
Here code similar to what I have :
NSMutableString *myString = [[NSMutableString alloc] initWithString:#"This is my String"];
[myString substringFromIndex:5];
NSLog(#"myString = %#", myString); //will output This is my String
If I use substringFromIndex on NSString it will work, for example like so :
NSString *tempStr = [[NSString alloc] init];
tempStr = [myString substringFromIndex:5];
NSLog(#"tempStr = %#", tempStr); //will output is my String
Why does it not work in the first example, and I have one more question, if I do it using the second method, and then I set:
[myString setString:tempStr];
[tempStr release];
This will result in a crash, I thought, since I used setString on NSMutableString, that I do not need the NSString and I release it, but apparently that is not the case, however if I use autorelease it will be OK
That method never alters the string you call it on. It returns a new string in both cases. So assign it to a new string variable and your good.
It's crashing because you over releasing one object and and leaking another. You alloc the first string, then make a new autoreleased string from substringFromIndex:, then release it. You dont need to try this hard.
Simply assign the output of the substring method to a variable, and let it be autoreleased for you. No alloc, no release.
A full proper example might look like this:
NSMutableString *myString = [[NSMutableString alloc] initWithString:#"This is my String"];
NSString *tmpString = [myString substringFromIndex:5];
NSLog(#"tempStr = %#", tempString);
[myString setString:tempStr];
// later do [myString release]
or even simpler:
NSString *myString = #"This is my String";
myString = [myString substringFromIndex:5];
You create an NSMutableString specifically so you CAN modify it.
But no one knows any way to do this:
[myMutableString substringFromIndex:5];
And if you are going to do this instead:
myMutableString = [myMutableString substringFromIndex:5];
why even use a mutable in the first place.
MutableStrings are great for ADDING (appending) to them.
Not sure why we can't also shorten (substring) them. (Without making a new copy.)
[myString substringFromIndex:5] returns a new NSString that starts from the specified index. It does not modify myString.
try this code instead:
NSLog(#"myString = %#", [myString substringFromIndex:5]);

Resources