I'm implementing a calendar as part of my app, it shows the selected date in nslog, but I need to send this value to a label,
it show the value as 2011-02-08 in nslog
I created a label in ib,(and connect to it)
in *ViewController.h
IBOutlet UILabel *dateis;
in *ViewController.m
- (void)calendarView:(KLCalendarView *)calendarView tappedTile:(KLTile *)aTile{
NSLog(#"Date Selected is %#",[aTile date]);
[aTile flash];
dateis = [aTile date];
}
but I get the warning>
Incompatible Objective-C types assigning 'struct KLDate *', expected 'struct UILabel *'
EDIT, if I use
dateis.text = [aTile date];
I get the warning
incompatible Objective-C types 'struct KLDate *', expected 'struct NSString *' when passing argument 1 of 'setText:' from distinct Objective-C type
KLDate is the way the date was defined in the calendar,
so how can I pass this value to the label (working on nslog, view code call in *.m)
Thanks a lot!!
You can't just assign a "Date" to a "Label"...
You are obviously using Appcelerator framework. (KLDate type)
So what you are looking for is :
dateis.text = [NSString stringWithFormat:#"%#", aTile.date];
stringWithFormat: will in fact invoke descriptionmethod of KLDate, so you can also use the equivalent :
dateis.text = aTile.date.description;
To find this look at KLDate.h and check wich method returns a NSString * that you can assign to the good property of UILabel (look its documentation) which is text
You should check description method implementation if you need to write your own code to format the date...
try:
dateis.text = [aTile date];
Well, NSLog can take a lot of different class types as input and it figures out what it can display. What is a KLTile? How are you assigning the date to the KLTile, i.e. from what data structure to what data structure. Somewhere there's gotta be a NSString or a formatted NSDate. Maybe you can see the internal structure of a KLTile in the debugger.
ok, so I dont know if is the proper thing to do, but its working!!
(please enlighten me to know if is fine!)
I just figured that if label wanted a string, then I will give it a string, haha, so,
- (void)calendarView:(KLCalendarView *)calendarView tappedTile:(KLTile *)aTile{
NSLog(#"Date Selected is %#",[aTile date]);
[aTile flash];
NSString *str =[NSString stringWithFormat:#"%#", [aTile date]];
dateis.text = str;
}
Related
in an ios application, I am trying to allow the user to enter a number and a format and I want to get a string with that number formatted as the user specified:
For that I have tried this:
- (NSString *)formatNumber:(NSNumber *)number withFormat:(NSString *)format
{
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setPositiveFormat:format];
NSString *formatedString = [formatter stringFromNumber:number];
return formatedString;
}
but if I try to call something like this:
NSNumber *number = [NSNumber numberWithDouble:1234567890];
NSString *string = [self formatNumber:number withFormat:#"###-###-####"];
I was expecting to get a result: 123-456-7890
But it is not working.
is the #"###-###-####" format wrong syntax ? or am I using the NSNumberFormatter wrong?
Thanks for any help
PS: I do not want to hard code an algorithm to loop through the characters and insert the dashes (-) because that format is just an example as the user is able to freely change it.
Thanks
EDIT
SORRY while writting my code here I missed a line. now added it
This may be useful:
https://discussions.apple.com/thread/2399192
Key quote:
Parentheses and dashes are not allowed in a number format.
I am a mere beginner in iPhone Programming. I have seen this code in a tutorial which I didn't understand what does it means. I am confused about keywords such as titleForState and initWithFormat.
Can anyone help me to understand the meaning and importance of this syntax.
-(IBAction)buttonPressed: (id)sender {
NSString *title = [sender **titleForState**:UIControlStateNormal];
NSString *newText = [[NSString alloc] **initWithFormat**:
#"%# button pressed.", title];
statusText.text = newText;//statustext is a label
[newText release];
}
initwithFormat allows you to modify a string by adding a variable's value to it, you can add as many variables as you like but you have to add the correct symbol for the correct primitive type. Here are some examples
NSString *thisIsAString = #"String";
float thisIsAFloat = 13.9f;
NSString *strFormat = [[NSString alloc] initWithFormat:#"This is a %#, this is a %f float", thisIsAString, thisIsAFloat];
NSLog(#"%#", strFormat);
This will produce the output This is a String, this is a 13.9f float notice the float and the NSString value have replaced the symbols.
The titleForState is getting the title of an object that has that method. This will return the title for lets say a UIButton that has a title of "Press" for UIControlStateNormal so the value "Press" will be entered into the NSString title. Not though that not everything in sender has the method titleForState the reason this will show up is because sender is a primitive type of id this will cause and error if something is sent that hasn't got titleForState and your app will crash.
I have built one 'deep' NSMutableDictionary that contains parsed XML data along with other relevant information that I can pass from one view controller to another. The NSMutableDictionary contains mostly NSStrings but also another NSMutableDictionary more NSStrings and finally followed even deeper with an NSMutableArray of custom objects (it's for a calendar).
Now, because it is a calendar, there are obviously dates involved. The XML data that I receive and parse using NSXMLParser returns strings, so it was on me to convert the day's date to usable numbers. The date in XML comes in with the following format: "MM.DD" I created the following method to do so:
- (void)createDateCodesWithString:(NSString *)string
{
NSInteger monthCode;
NSInteger dayCode;
....
NSArray *dates = [string componentsSeparatedByString:#"."];
monthCode = [[dates objectAtIndex:0] integerValue];
dayCode = [[dates objectAtIndex:1] integerValue];
....
shortDay = [NSNumber numberWithInt:dayCode];
}
'shortDay' is a NSNumber* and an ivar and set as a property (nonatomic, retain) for the custom object that I have created. When I run NSLog commands in the console, it appears that 'shortDay' and other data has been stored successfully in the deep NSMutableDictionary. I run in to problems, however, when I try to access the data again. When I access a NSString* stored ivar, things work OK, but when I attempt to access the NSNumber* I am given the error EXC_BAD_ACCESS with either code 1 or code 2. This is how I try to call upon the NSNumber*
NSNumber *number = day.shortDay;
return [number stringValue];
Might the problem be because the NSArray *dates strips the string into month and day strings and the day string, being two characters long, may contain a '0' before, say, a '6' if the day is the 6th of the month? Any advice?
I am happy to post more code if needed.
It's possible that the memory for shortDay is being cleaned up before the next time you try to access it. When assigning it, try this instead:
shortDay = [[NSNumber numberWithInt:dayCode] retain];
to increase the reference count (AKA take ownership of the object) to avoid the memory being deallocated too early.
If this resolves the problem, you will then need to call [shortDay release] in the dealloc method of your class, such that the memory for it will be properly deallocated at the right time.
So I'd like to access and display a formatted date outside my function. For the date format I am using NSDateFormatter which works fine..
My function (didFinishUpdatesSuccessfully) performs some action and if successful displays an UIAlertView which includes the formatted date. All that works fine..
- (void) didFinishUpdatesSuccessfully {
//--- Create formatted date
NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"dd/MM/YYYY - hh:mm:ss a"];
NSString *dateString = [dateFormatter stringFromDate:currDate]; // dateString contains the current date as a string
[dateFormatter release];
//--- UIAlertView
NSString *title = #"The update has been performed!";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: title
message: dateString
delegate: nil
cancelButtonTitle: [FileUtils appResourceForKey:#"UPDATE_GENERAL_BUTTON_TITLE_OK"]
otherButtonTitles: nil];
[alert show];
[alert release];
//--- create new string
// NSMutableString* lastUpdated = [NSMutableString stringWithFormat:#"%#",dateString];
}
I now want to write the value of dateString into a global NSString or NSMutableString and access it somewhere else in the code, e.g. another function etc..
I thought about creating a NSMutableString like this:
NSMutableString* lastUpdated = [NSMutableString stringWithFormat:#"%#",dateString]; and to access lastUpdated somewhere else, but ouside of this function lastUpdated is empty... Can you help? Cheers
NSMutableString* lastUpdated = [NSMutableString stringWithFormat:#"%#",dateString];
If you do that, you're declaring a local variable named lastUpdated. Even if there's another global variable with the same name, this local one will hide the global variable for as long as it's in scope (the life of your function).
To make this work, you need to declare a global lastUpdated somewhere outside of any function or method, probably near the top of a .m file:
NSMutableString *lastUpdated;
You can then access that variable from anywhere in the .m file. If you want to access it in other .m files, you'll want to add an extern declaration in the corresponding header (.h) file:
extern NSMutableString *lastUpdated;
With that declaration, you can use lastUpdated in any file that includes that header file.
Two things to know:
This is basic C stuff, so if it seems unfamiliar, you should review scope rules for C. Know the difference between a global variable, a static variable, a local variable, an instance variable (okay, plain old C doesn't have those), and a parameter.
Global variables are horrible. Don't trust anybody who tells you otherwise. I offer the advice above to help solve your immediate problem, but a better solution would be to figure out how to refactor your code so that you can avoid the need for a global variable. (And IMO a singleton isn't the answer, either. Singletons used just to access global data aren't much more than fancy-pants global variables.)
You should retain the string like.
NSMutableString* lastUpdated;
lastUpdated = [[NSMutableString stringWithFormat:#"%#",dateString] retain];
Now try to access in outside.
I'm using this code to query core data and return the value of key, I store the value like this :
NSString *newName= #"test";
[newShot setValue:newName forKey:#"shotNumber"];
and I query like this :
NSManagedObject *mo = [items objectAtIndex:0]; // assuming that array is not empty
NSString *value = [[mo valueForKey:#"shotNumber"] stringValue];
NSLog(#"Value : %#",value);
I'm crashing with this message though :
[NSCFString stringValue]: unrecognized selector sent to instance,
does anyone know where that would be coming from ?
newName (#"test") is already an NSString. There is no need to call -stringValue to convert it to a string.
NSString *value = [mo valueForKey:#"shotNumber"];
I often times add a category for NSString to handle this:
#interface NSString(JB)
-(NSString *) stringValue;
#end
#implementation NSString(JB)
-(NSString *) stringValue {
return self;
}
#end
You can add a similar category to other classes that you want to respond this way.
[mo valueForKey: #"shotNumber"] is returning a string and NSString (of which NSCFString is an implementation detail) do not implement a stringValue method.
Given that NSNumber does implement stringValue, I'd bet you put an NSString into mo when you thought you were putting in an NSNumber.
The value for the key #"shotNumber" is probably of type NSString which is just a wrapper for NSCFString. What you need to do, is, instead of stringValue, use the description method.
Note that you could also get this problem if you are trying to access a string property on an object that you think is something else, but is actually a string.
In my case I thought my Hydration object was in fact a hydration, but checking its class via isKindOfClass I found that it was an NSString and realized that I had incorrectly cast it as a Hydration object and that my problem lied further up the chain.