String value cannot assigned to a string variable in iphone? - ios4

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;

Related

Unable to load NSMutableArray from CoreData store

I have a NSMUtableArray that I am trying to load from a Core Data store (there is valid data in the store); this is the code:
[unsortedArray addObject:storedServices.aCustomServices1];
[unsortedArray addObject:storedServices.aCustomServices2];
The array is defined as:
#property (nonatomic, retain) NSMutableArray *unsortedArray;
I can load the array using static data which works:
unsortedArray = [NSMutableArray arrayWithObjects:
NSLocalizedString(#"Property1",nil),
NSLocalizedString(#"Property2",nil),nil];
The problem is although there is valid data in the CD store, the array remains empty. I have searched Google and SO but found nothing related. Why can I not load from the Core Data store?
I'll take a punt that you haven't allocated unsortedArray. Try:
self.unsortedArray = [NSMutableArray array];
[self.unsortedArray addObject:storedServices.aCustomServices1];
[self.unsortedArray addObject:storedServices.aCustomServices2];
This assumes you have unsortedArray getter/setter methods that conform to normal MRR memory management practices. This is as simple as using #synthesize unsortedArray (although newer versions of clang do this for you, I'd still explicitly add it).
Note that:
self.unsortedArray = [NSMutableArray array];
Should be in your init method.

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

NSDate value not accessible across methods

Am sorry to ask such a trivial question. Am a newbie to Objective-C, & simply cannot see how to get this working, after having tried several possible ways & google'd around for it. Please help!
My question is simple. I have a class-level NSDate object, which is declared outside any method in the class as:
NSDate *fromDate;
Now, within a method, am setting this value to the date from a DatePicker as:
fromDate = [datePicker date];
Soon after the above assignment, I print its value into the log & it works fine.
NSLog(#"From Date: %#", fromDate);
Now, when I use NSDate's value in another/different method, the value's gone! Why is it not persisted across methods in the same class itself? What can I do for the value to be accessible across methods?
Thanks for your reply.
Hi Remy,
I didn't know Objective-C didn't have class-level variables! Thanks for pointing it out!
Yes, I've set the project (in Xcode) to do ARC (so, I believe that should take care).
Here is the code:
In ViewController.h
....
....
#property (nonatomic, retain) NSDate *historyFromDate;
#property (nonatomic, retain) NSDate *historyToDate;
....
....
-(IBAction) fromDateChosen: (id)sender;
-(void) fetchTheHistory;
In ViewController.m
...
...
#synthesize historyFromDate;
#synthesize historyToDate;
....
....
-(IBAction) fromDateChosen: (id)sender {
NSString *buttonTitle = #"I've chosen the 'FROM' date";
if ([[buttonDateChosen currentTitle] isEqualToString:buttonTitle]) {
NSLog(#"User has chosen the 'From' date");
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
// Get the chosen date value
NSDate *fromDate = [datePicker date];
historyFromDate = fromDate;
// Set the 'to' date label to reflect the user's choice
labelFromDate.text = [dateFormatter stringFromDate:historyFromDate];
NSLog(#"'From' Date Chosen:%#", historyFromDate);
//[dateFormatter stringFromDate:[datePicker date]]);
[self fetchTheMoodHistory];
}
}
...
...
...
-(void) fetchTheHistory {
NSLog(#"Calling fetchTheHistory for the period from %#", historyFromDate);
...
...
}
...
...
fromDateChosen gets called after the user chooses a date form a Date Picker object in the UI.
Within the method 'fromDateChosen', when I print the historyFromDate, the value is correct.
But, when I print it in fetchTheHistory method, the value shows the current date/time (not the one the user chose).
The date property of UIDatePicker is retained by that class, and will be accessible as long as the date picker itself is in scope and valid (not been released). You are storing this date value in a variable, but not retaining it yourself, so when the date picker goes out of scope you lose the value. As a quick fix, do this instead;
fromDate = [[datePicker date] retain];
Now, this is not the best approach, you really should be making the date a property of whatever class is using this information.
Try put the fromDate variable under class scope, e.g:
#implementation ViewController
{
NSDate *fromDate;
}

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...

Invalid receiver type 'NSUInteger'

I have a Core Data entity whose header file looks like this:
#interface MyEntity : NSManagedObject
{
}
#property (nonatomic, retain) NSNumber * index;
#end
And it's implementation file looks like this:
#implementation MyEntity
#dynamic index;
#end
Now, I have a piece of code that looks like this:
NSArray* selectedObects = [myEntityArrayController selectedObjects];
NSUInteger theIndex = [[[selectedObects objectAtIndex:0] index] unsignedIntegerValue];
The 'myEntityArrayController' object is a NSArrayController which manages all entities of MyEntity. This code executes correctly, however XCode always gives the warning "Invalid receiver type 'NSUInteger'" for the last line of code. For some reason, XCode thinks that the index method returns a NSUInteger. I'm not sure why it thinks this, because 'objectAtIndex' returns an object of type 'id'.
I've cleaned the project several times, and these warnings have hung around for a while. Any suggestions are appreciated.
Unroll your code so that each message is on its own line and then walk through it with the debugger to make sure every object is what you think it is.

Resources