iOS4 - trying to change a string value - ios4

I need to change a string value if it meets certain criteria, but I'm not having any luck so far. I'm not sure if it's the input string or if I'm doing something fundamentally wrong - here's my code:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSMutableString *stadium = [NSMutableString stringWithString:[prefs stringForKey:#"stadiumname"]];
NSLog(#"stadium: %#", stadium);
if([prefs stringForKey:#"stadiumname"]==#"Brighton & Hove")
{
[stadium setString:#"Hove"];
}
if([prefs stringForKey:#"stadiumname"]==#"Monmore Green")
{
[stadium setString:#"Monmore"];
}
NSLog(#"stadium: %#", stadium);
In the NSLog output on both sides I still get "Brighton & Hove" or "Monmore Green", rather than just "Hove" or "Monmore" as I was expecting. I've tried changing the input field to allow for possible encoding by doing:
NSMutableString *stadium = [NSMutableString stringWithString:[[prefs stringForKey:#"stadiumname"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
but that makes no difference. Would NSLog show up any encoding in the string anyway?
I just need to be able to use the shortened string once it comes out the other side, but so far no luck.
Can anyone enlighten me?

it's because of how you compare the string, so instead of
if([prefs stringForKey:#"stadiumname"]==#"Brighton & Hove")
use
if([[prefs stringForKey:#"stadiumname"] isEqualToString:#"Brighton & Hove"])

Related

UISearchBar textDidChange, searchtext variable unusable with rangeOfString?

I have been searching for hours and no solution in sight... I am filtering an array of custom objects using the text typed into a UISearchBar to change the data in the tableview below.
After a bit of debugging, ive pin pointed the source of my troubles:
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
var temp = "c"
FilterResults = SearchResults.filter {
return $0.Username.rangeOfString(temp) != nil
}
}
here is my trouble: If I used a temp that is explicitely defined as above , where temp = "c", it happily matches all the user names that have a c in it! The issue arises when instead of using temp, I used the variable searchText, in that cases it never EVER matches with anything! I checked and searchText is not null, in fact I printed out searchText in tests and it printed out a normal string (Based on what is typed in the search bar), but for some crazy reason, if I use the searchText variable inside the .rangeOfString method, it always returns false! Why is that? Ive also used searchBar.text and it gave me the same troubles... I am completely lost and frustrated. Any help would be much appreciated!
Try this if it works.
var searchList = [String]()
let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %#", searchText!)
let array = (searchList as NSArray).filteredArrayUsingPredicate(searchPredicate) as! [String]
Turns out it was because I didn't realize that the rangeOfString search is case sensitive!

Checking what a value is in SSJS

I have this block of code in SSJS that I'm doing some field validation stuff:
thisDoc is a NoteXspDocument
fld = the name of a field
var thisValue = thisDoc.getValue(fld);
print("Check Text = " + thisValue);
print("Is is a Date " + (thisValue === Date))
when I run it the log has this:
Check Text = 09/10/15 12:00 PM
Is is a Date false
In this code I do not know what the datatype is of the fld which is a field name. I check the backend document and get the NotesItem.Type() and this field is of type text 1280 in the backend, but the NotesXspDocument has a date. I need to determine what the data type is thisValue sure acts like a NotesDateTime object, but I'm doing something wrong somewhere.
I think the issue might be the difference between a NotesDateTime and a java.util.Date but they drive me up the wall.
Further Edit --
The problem is that I have an Array of field names var Fields:Array that I then loop through and get fld = Fields[n] so when I get the value of the field it could be anything Text, Date, Number so when I do var thisValue = thisDoc.getValue(fld) or thisDoc.getItemValue(fld) I need to figure out what kind of value I have. I guess I could put the getItem..... inside a try until I find one that works but that seems like a less than optimum solution.
Try instanceof Date.class. What you've got is not checking the data type of thisValue against the underlying class, instead it's checking the object itself.
Because the field that I am retrieving can be just about anything I use
var thisValue = thisdoc.getValue(fld);
i had a lot of trouble then determining what kind of data I had. It could be a null Date/Number/String So the first thing I did was find out what the backend data type was:
var thisItem:NotesItem = thisDoc.getDocument().getFirstItem(fld);
var type:Integer = thisItem.getType()
This helps somewhat if the field has been previously set, but if it is a new document or the field has not received a value yet it will be type 1280 or text and probably null.
So my fisrt test is for null or "". then it becomes a bit tougher because I need to test for some values. In all my comboboxs I add the text "--- Select ?????" as the first item in the list so I tried to get a substring of "---" but because of variance in the datatype I needed to put that in a try:
try{
if (thisValue.substring(0,3) == "---"){
print("have null Prefix");
rtn = false;
errMsg.push("The field " + fld + " is a Required Field please enter a value");
break;
}catch(e){ etc
I then wrapped the various other datatype tests in trys and now I have it working.
Might be a better way but this works.
Use .getItemValue() to return a vector array, then test the data type. You can also try .getItemValueString() to return a text string or .getItemValueDate() or .getItemValueDateTime() to return date/time.
Since getItemValue() returns an array, use subscript to get the first element:
var thisValue = thisDoc.getItemValue(fld);
var thisIsDate = (thisValue[0] instanceof Date);
print("Check Text = " + thisValue[0]);
print("Is this a Date ? " + thisIsDate;

Swift: Converting NSNumber into NSString (NSNumber is not a subtype of NSString)

In my app, I'm going into CoreData and grabbing an entry whose type is a Double, then I'm trying to put that value into a text field in my app.
This looks like
lengthTextField.text = lastSession.length but I'm getting the error NSNumber is not a subtype of NSString
The value of lastSession.length is 6.0 for reference. Any suggestions on how to properly put that data in my text field?
Thanks!
In core data numbers are backed by NSNumber. You can view the documentation here
In swift you can access the string representation of the number through the instance property stringValue
lengthTextField.text = lastSession.length.stringValue
You'll have to format the NSNumber's doubleValue member to a string before outputting.
let x:NSNumber = 6.0
let s:String = String(format:"%f", x.doubleValue) //formats the string to accept double/float
println(s)

Undo operation with NSUndoManager in rich UITextView (iOS 6)

I want to change some or all of the attributed text of a rich UITextView (iOS 6), and allow the user to undo the change.
After reading NSUndoManager documentation, I tried the first way:
“Simple undo” based on a simple selector with a single object argument.
I expected an undo operation to be as simple as:
Declare this method:
- (void)setAttributedStringToTextView:(NSAttributedString *)newAttributedString {
NSAttributedString *currentAttributedString = self.textView.attributedText;
if (! [currentAttributedString isEqualToAttributedString:newAttributedString]) {
[self.textView.undoManager registerUndoWithTarget:self
selector:#selector(setAttributedStringToTextView:)
object:currentAttributedString];
[self.textView.undoManager setActionName:#"Attributed string change"];
[self.textView setAttributedText:newAttributedString];
}
}
Change the text in my UITextView by calling:
[self setAttributedStringToTextView:mutableAttributedString];
But after doing that, NSUndoManager says it cannot undo.
NSLog(#"Can undo: %d", [self.textView.undoManager canUndo]);
// Prints: "Can undo: 0"
So I tried the second way:
“Invocation-based undo” which uses an NSInvocation object.
Declare this:
- (void)setMyTextViewAttributedString:(NSAttributedString *)newAttributedString {
NSAttributedString *currentAttributedString = [self.textView attributedText];
if (! [currentAttributedString isEqualToAttributedString:newAttributedString]) {
[[self.textView.undoManager prepareWithInvocationTarget:self]
setMyTextViewAttributedString:currentAttributedString];
[self.textView.undoManager setActionName:#"Attributed string change"];
[self.textView setAttributedText:newAttributedString];
}
}
and change the text with:
[self setMyTextViewAttributedString:mutableAttributedString];
After that, NSUndoManager also says it cannot undo.
Why?
Note that the user is editing the UITextView when triggering the code that will change the attributed text.
A workaround would be to replace the text directly via UITextInput protocol method. The following method is quite convenient, but I haven't found an equivalent for NSAttributedString. Did I miss it?
- (void)replaceRange:(UITextRange *)range withText:(NSString *)text
An hack suggested here is to simulate a paste operation. If possible, I would prefer to avoid this (no reason yet, just feels too dirty to not come back bite me later).
I'm kinda still in shock this works. I posted the same answer over here UITextView undo manager do not work with replacement attributed string (iOS 6).
- (void)applyAttributesToSelection:(NSDictionary*)attributes {
UITextView *textView = self.contentCell.textView;
NSRange selectedRange = textView.selectedRange;
UITextRange *selectedTextRange = textView.selectedTextRange;
NSAttributedString *selectedText = [textView.textStorage attributedSubstringFromRange:selectedRange];
[textView.undoManager beginUndoGrouping];
[textView replaceRange:selectedTextRange withText:selectedText.string];
[textView.textStorage addAttributes:attributes range:selectedRange];
[textView.undoManager endUndoGrouping];
[textView setTypingAttributes:attributes];
}

objective c appending string cocos2d

Hello I am writing an application and I want to create a string.
so I use that
NSString *scoreString;
NSString *cupCakesPassedString;
NSString *cupCakes;
int cupCakesPassed;
int totalCupCakesPerLevel;
-(void)spriteMoveFinished:(id)sender {
CCSprite *sprite = (CCSprite *)sender;
[self removeChild:sprite cleanup:YES];
if (sprite.position.y <= 0) {
sprite.position = ccp( sprite.position.x,768 );
score+=5;
scoreString=[NSString stringWithFormat:#"%i",score];
[label setString:scoreString];
cupCakesPassed++;
cupCakesPassedString=[NSString stringWithFormat:#"%i",cupCakesPassed];
cupCakes=[[cupCakesPassedString stringByAppendingString:#"/"]stringByAppendingString:totalCupCakes];
[passingCupCakes setString:cupCakes];
}
}
it crashes!! but if use another string like scoreString it works...
in init method I have
totalCupCakesPerLevel=30;
scoreString=[NSString stringWithFormat:#"%i",score];
cupCakesPassedString=[NSString stringWithFormat:#"%i",cupCakesPassed];
totalCupCakes = [NSString stringWithFormat:#"%i",7];
cupCakes=[[cupCakesPassedString stringByAppendingString:#"/"]stringByAppendingString:totalCupCakes];
if I do this
cupCakes=[[cupCakesPassedString stringByAppendingString:#"/"]stringByAppendingString:scoreString];
I also has in init method that
cupCakes=[[cupCakesPassedString stringByAppendingString:#"/"]stringByAppendingString:totalCupCakes];
and actually works...until the method is called.
the numbers might be wrong but are for testing purposes
it seems that the problem is with string totalCupCakes,since even if I use #"test" works but what is wrong with that string?
Using a string method like this:
cupcakes = [NSString stringWithFormat:#"%d/%d", cupCakesPassed, totalCupCakes];
Would be simpler to use instead of the appending strings.
If I understand right, all your problems are because of non-retained strings. All stringWith... constructors of NSString class returns autoreleased objects. Retain them after creation and release in your dealloc method.
In your case to the moment of calling method, strings are deallocated and are not valid objects

Resources