objective c appending string cocos2d - string

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

Related

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)

Converting an object of an array

I have the following block of codes in my program.
for(int k=0;k<reqroom.count;k++)
{
NSString *rent=[roomRent objectAtIndex:k];
NSString *tax=[roomTax objectAtIndex:k];
NSString *no=[textvaluearray objectAtIndex:k];
NSDecimalNumber *rentd=[NSDecimalNumber decimalNumberWithString:rent];
}
//here roomRent,roomTax and textvaluearray are NSMutableArrays
This is the error that I am receiving:
'NSInvalidArgumentException', reason: '-[__NSArrayI length]: unrecognized selector sent to instance 0x81b2ce0'
Thanks in advance.
From the exception "-[__NSArrayI length]:" it looks like "rent" object is not a string type and its array. Can you check the type of "rent" before converting to decimal.
What is reqroom? Is it an NSString or NSArray (or NSMutableArray)? If it's some sort of array and you want to iterate as many times as there are objects in the array, you should probably do something like
for(int k=0;k<[reqroom count];k++)

Key-Value Type Coercion in iOS

I am writing an application using Core Data which heavily depends on setting attributes from string values. However, I am running into a problem because Core Data, when it creates wrapper methods, uses NSNumber to represent all of the numeric fields. Therefore, if I pass in a String using key/value coding setValue:forKey: it gives me a type error:
For instance, I have an object type "Building". In the datamodel, I have an attribute called "fbFloors" set to integer 32.
Then, in my code, I do the following:
Building * b = [NSEntityDescription insertNewObjectForEntityForName:#"Building" inManagedObjectContext:ctx];
[b setValue:#"2" forKey:#"fbFloors"];
This raises the following exception:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unacceptable type of value for attribute: property = "fbFloors"; desired type = NSNumber; given type = __NSCFConstantString; value = 2.'
I would like it to coerce the string value to a number, but it doesn't want to. I tried implementing coerceValueForFbFloors: but it looks like that is only available in Mac OS X, not iOS.
Any ideas?
What if you did something like this...
- (NSNumber*)fbFloorsValue:(NSString*)valueString
{
return [NSNumber numberWithInteger: [valueString integerValue]];
}
where you have a method for each non-string attribute. Then when you set those values in a generic way...
Assume your key ("fbFloors") is in a variable called and your value ("2") is in a variable called ...
id valueObject;
SEL selector = NSSelectorFromString([NSString stringWithFormat:#"%#Value:", key]);
if (selector && [self respondsToSelector:selector]) {
valueObject = [self performSelector:selector withObject:value];
} else {
valueObject = value;
}
Building * b = [NSEntityDescription insertNewObjectForEntityForName:#"Building" inManagedObjectContext:ctx]; [b setValue:valueObject forKey:#key];
You have to pass an actual instance of NSNumber to setValue. Something like:
[b setValue[NSNumber numberWithInt:2] forKey:#"fbFloors"];
If your data is appearing as a string, then you can use NSNumberFormatter to convert it first to an NSNumber.

String value cannot assigned to a string variable in iphone?

In my application, I take a UITextField value and trim it and assign to a string Variable declared in an Appdelegate. It assigns to a appdelegate variable and works well, sometimes It does not assign to the appdelegate variable.(This value is used in another view,so declared in appdelegate). Plz help...
NSString *txtTemp=[NSString stringWithFormat:#"%#",[txtName.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
txtName.text=txtTemp;
[self appDelegate].customSearchQuery=[NSString stringWithFormat:#"%#",txtTemp];
NSLog(#"--appDelegate.customSearchQuery =%#",appDelegate.customSearchQuery);
This is most probably a memory management problem.
NSString creates an autoreleased object. You will have to retain it if you want to use it outside the method you showed above. The easiest thing is to delcare as
#property (nonatomic, retain) NSString *customSearchQuery;
in your Appdelegate.h. That should do the trick.
In the dealloc-method of the appdelegate, you'll need to release it - otherwise you leak the NSString; with the declaration above, you'll add
customSearchQuery = nil;

NSString within a link

I have a UIWebView that loads a link, http://www.google.com/a/datacommsales.net. But I want to have the datacommsales.net part interchangable. What I would like it to be is http://www.google.com/a/stringOne, stringOne being the NSString, so I can set the value of the string and change the link without editing the code. But the link is inside quotes, #"http://www.google.com/a/datacommsales.net", so it doesn't recognize the string. How could I include the string's value as part of the link? Any help is appreciated.
EDIT
To be a little more specific, here's my code:
- (IBAction)refreshNow:(id)sender
{
NSString *variablePart = #"secondpart.com";
NSString *page = [NSString stringWithFormat:#"google.com/a/variablePart/docs"];
[webView loadHTMLString:page baseURL:nil];
}
How would I put the string variablePart in the link like that?
do you mean just something like
NSString *variablePart = #"secondpart.com";
NSString *url = [#"http://www.google.com/" stringByAppendingString:variablePart];
EDIT:
NSString *variablePart = #"secondpart.com";
[NSString stringWithFormat:#"google.com/a/%#/docs", variablePart];
Checks the NSString stringWithFormat method... Or explain a little more how you do your stuff...

Resources