deleteCharactersInRange work something wrong - iphone

HI all! I am using message deleteCharactersInRange from NSMutableString. And there is a problem that this finction deletes range in a wrong way.
Here is a sample of code that works wrong:
-(void) btnClick
{
NSRange deleteRange = NSMakeRange(0, 1);
[valueStr deleteCharactersInRange:deleteRange];
[self ShowNumber];
}
I have a mutable string: "-21.256" and when I press the button btnClick it must delete "-" from the begining but it does it only after the 5th presses time. Ealier it worked fine, but now no. Help please, or what can I use instead this function? Thanx!

Your code should work just fine:
NSMutableString *string = [NSMutableString stringWithString:#"-21.256"];
NSLog(#"%#", string);
[string deleteCharactersInRange:NSMakeRange(0, 1)];
NSLog(#"%#", string);
results in:
-21.256
21.256
Your problem must be elsewhere.

I think it will be interesting to you.
I itinialized my string in a such way:
NSString *buf = nil;
buf = [NSString stringWithFormat:#"%14.5f", myCalculator.calcValue];
after that I add this string to my NSMutableString. And with string I did operations with the help of func:
[string deleteCharactersInRange:NSMakeRange(0, 1)];
But charachters were deleted only after the 6 or 7 cycle of clicking.
Solution:
The problem is in #"%14.5f" in this string we have:
" -2.00000"instead of "-2.00000" so function does her work well, but it deleted white spaces instead of "-".
So we need to convert in such way: #"%f"

Related

How To Detect If Array Displays These Results

How would I detect if an array displays the following in an if statement? (I tried NULL and it didn't work)...
When I NSLog the description of the array, this is what returns:
NSLog(#"%#", [manager purDesc]description]);
2011-08-30 13:43:20.227 PROJECT[2921:f503] manager purDesc Dump:(
{
amt = "\n ";
desc = "\n ";
}
)
I need to say "If [manager purDesc] looks like that, display a UIAlertView".
Sorry everyone, I feel like I'm having trouble getting my point across this morning. If you don't understand, please comment with your question and I'll try to explain better.
Actually, your structure seems to be a dictionary inside an array. Not sure how that all stacks up. To see if all items in a dictionary are only whitespace.
BOOL empty = YES;
NSCharacterSet* wp = [NSCharacterSet whitespaceAndNewlineCharacterSet];
for(NSString* key in dict)
{
NSString* val = [dict objectForKey: key];
// trim white space and check length
if([[val stringByTrimmingCharactersInSet: wp]length])
{
empty = NO;
break;
}
}
the array version is left as an exercise to the reader. :-)
If those fields are NSString, you might want to check out stringByTrimmingCharactersInSet:.
NSString* trimmedAmount = [amt stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
You can remove whitespace and returns by using the NSString method stringByTrimmingCharactersInSet: along with the static set whitespaceAndNewlineCharacterSet.
However, based on the output of [purDesc description], it looks like you may have an NSDictionary, not an array.
Why don't you check the actual elements of the array? somehting like
[manager objecAtIndex:0] = nil

how to append String To Mutable string

Hi i am new to iphone development,can any one help how to append string to mutable string.
im trying to string By appending String Format .application Is crashes...
Sample code NSMutableString:
NSMutableString* mutString = [[NSMutableString alloc] init];
for(int index=0;index<10;index++)
{
[mutString appendString:[NSString stringWithFormat:#"%d",index]];
}
NSLog(#"Content in MutableString: %#",mutString);
Regarding crash: post your code that crashes. What does it say ?
There is a crash when you try to append nil to a NSMutableString - check that.
Also while it does not crash during append - if your NSMutablestring is not initialized - then nothing works and your app might crash later in the code because there is nothing in your string.
Post the crash report, I am sure it will tell you what is going wrong.

iPhone Objective C - How to remove URLs from an NSString

I am looking for an efficient way to replace URLs in an NSString (or NSMutableString) with the replacement word 'link', for example ...
#"This is a sample with **http://bitbanter.com** within the string and heres another **http://spikyorange.co.uk** for luck"
I would like this to become...
#"This is a sample with **'link'** within the string and heres another **'link'** for luck"
Ideally, I would like this to be some sort of method that accepts regular expressions, but, this needs to work on the iPhone, preferably without any libraries, or, I could be persuaded if the library was tiny.
Other features that would be handy, replace #"OMG" with #"Oh my God", but not when it's part of a word, i.e. #"DOOMGAME" shouldn't be touched.
Any suggestions appreciated.
Regards,
Rob.
This was actually quite a bit of fun to play with and hopefully the solution is somehow what you were looking for. This is flexible enough to cater not only for links, but also other patterns where you may want to replace a word for another using certain conditions:
I have commented most of the code so it should be pretty self explanatory. If not, feel free to leave a comment and I will try my best to help:
- (NSString*)replacePattern:(NSString*)pattern withReplacement:(NSString*)replacement forString:(NSString*)string usingCharacterSet:(NSCharacterSet*)characterSetOrNil
{
// Check if a NSCharacterSet has been provided, otherwise use our "default" one
if (!characterSetOrNil)
characterSetOrNil = [NSCharacterSet characterSetWithCharactersInString:#" !?,()]"];
// Create a mutable copy of the string supplied, setup all the default variables we'll need to use
NSMutableString *mutableString = [[[NSMutableString alloc] initWithString:string] autorelease];
NSString *beforePatternString = nil;
NSRange outputrange = NSMakeRange(0, 0);
// Check if the string contains the "pattern" you're looking for, otherwise simply return it.
NSRange containsPattern = [mutableString rangeOfString:pattern];
while (containsPattern.location != NSNotFound)
// Found the pattern, let's run with the changes
{
// Firstly, we grab the full string range
NSRange stringrange = NSMakeRange(0, [mutableString length]);
NSScanner *scanner = [[NSScanner alloc] initWithString:mutableString];
// Now we use NSScanner to scan UP TO the pattern provided
[scanner scanUpToString:pattern intoString:&beforePatternString];
// Check for nil here otherwise you will crash - you will get nil if the pattern is at the very beginning of the string
// outputrange represents the range of the string right BEFORE your pattern
// We need this to know where to start searching for our characterset (i.e. end of output range = beginning of our pattern)
if (beforePatternString != nil)
outputrange = [mutableString rangeOfString:beforePatternString];
// Search for any of the character sets supplied to know where to stop.
// i.e. for a URL you'd be looking at non-URL friendly characters, including spaces (this may need a bit more research for an exhaustive list)
NSRange characterAfterPatternRange = [mutableString rangeOfCharacterFromSet:characterSetOrNil options:NSLiteralSearch range:NSMakeRange(outputrange.length, stringrange.length-outputrange.length)];
// Check if the link is not at the very end of the string, in which case there will be no characters AFTER it so set the NSRage location to the end of the string (== it's length)
if (characterAfterPatternRange.location == NSNotFound)
characterAfterPatternRange.location = [mutableString length];
// Assign the pattern's start position and length, and then replace it with the pattern
NSInteger patternStartPosition = outputrange.length;
NSInteger patternLength = characterAfterPatternRange.location - outputrange.length;
[mutableString replaceCharactersInRange:NSMakeRange(patternStartPosition, patternLength) withString:replacement];
[scanner release];
// Reset containsPattern for new mutablestring and let the loop continue
containsPattern = [mutableString rangeOfString:pattern];
}
return [[mutableString copy] autorelease];
}
And to use your question as an example, here's how you could call it:
NSString *firstString = #"OMG!!!! this is the best convenience method ever, seriously! It even works with URLs like http://www.stackoverflow.com";
NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:#" !?,()]"];
NSString *returnedFirstString = [self replacePattern:#"OMG" withReplacement:#"Oh my God" forString:firstString usingCharacterSet:characterSet];
NSString *returnedSecondString = [self replacePattern:#"http://" withReplacement:#"LINK" forString:returnedFirstString usingCharacterSet:characterSet];
NSLog (#"Original string = %#\nFirst returned string = %#\nSecond returned string = %#", firstString, returnedFirstString, returnedSecondString);
I hope it helps!
Cheers,
Rog
As of iOS 4, NSRegularExpression is available. Amongst other things, you can enumerate all matches within a string via a block, allowing you to do whatever you want to each, or have the regular expression perform some kinds of substitution directly for you.
Direct string substitutions (like 'OMG' -> 'Oh my God') can be performed directly by an NSString, using -stringByReplacingOccurencesOfString:withString:, or replaceOccurrencesOfString:withString:options:range: if your string is mutable.

String not receiving new value is always (null)

Weird thing is happening here.
NSString *string = [powerPickerVC.powerList objectAtIndex:selRow];
NSLog(#"powerPicker row = %#", string); //this returns me the string from powerList
repVC.selectedPower = string; //selectedPower doesn't receive the new value and returns (null)
NSLog(#"selectedPower = %#", repVC.selectedPower);
And repVC.selectedPower is always returning (null)!
Just before that piece of code, I have this:
selectedRowPower = [powerPickerVC.powerPicker selectedRowInComponent:0];
repVC.selectedRowInObjectPicker = selectedRowPower;
NSLog(#"selectedRowInObjectPicker = %d", selectedRowPower);
And that works perfectly. selectedRowInObjectPicker is an NSInteger but if I'm able to set its value, why am I not being able to set selectedPower's value?
Yes, the object is synthesized and everything...
High chance that repVC is nil. Try to add breakpoint there and see.
Have you defined a method called -setSelectedPower: by any chance?
Use the [NSString stringWithString: ] to initialize strings.
In your case,
repVC.selectedPower = [[NSString stringWithString:string];
And ensure the receiver is a properly declared NSString as intended.

Potential Leaked Object Error

I'm getting a potentially leaked object error from the Static Analyzer for this line:
strCleanPhone = [[[[strPhone stringByReplacingOccurrencesOfString:#" " withString:#""]
stringByReplacingOccurrencesOfString:#"(" withString:#""]
stringByReplacingOccurrencesOfString:#")" withString:#""]
stringByReplacingOccurrencesOfString:#"-" withString:#""];
For one, is this the preferred way to strip non-numeric characters from a phone number string?
Two, can you possibly explain why this would be a leaked object?
The strings created by stringByReplacingOccurrencesOfString are autoreleased, so they aren't leaked. If there's a leak, it has to do with strPhone and strCleanPhone.
For example, if strCleanPhone is a #property with the retain option, and is currently not nil, then your code leaks it. To use the release/retain code that was generated by synthesize you have to use the property syntax: self.strCleanPhone = .... Using just strCleanPhone = ... sets the instance variable and doesn't release any object it was pointing to.
If you're on iOS 4.0+, you might be able to use the new NSRegularExpression object to do this a little more elegantly.
The code you have as posted doesn't leak. It just creates four autoreleased string objects.
If you are looking to strip out characters that are not numbers.
NSString *strPhone = #"(555) 444-3333";
NSMutableString *strCleanPhone = [NSMutableString string];
for (int i=0;i<[str length];i++)
{
unichar ch = [str characterAtIndex:i];
if (isnumber(ch)) [strCleanPhone appendFormat:#"%c", ch];
}
But I suggest looking into regular expressions.
Make sure you expand the analyzer warning by clicking the warning text in the source view! Chances are it's pointing to where a variable is last referenced; if you expand the warning you'll see a bunch of arrows indicating code flow, which will help indicate where you've allocated your potentially-leaked object.
(tl;dr: Post more code.)