conversion Nsstring - iphone

Hi all guys ,I am new in objective c and I need help, I read from my xml
file and I want convert my NSString to bool and NSString to date and
Nsstring to long
NSArray *names = [partyMember elementsForName:#"price"];
if (names.count > 0) {
GDataXMLElement *firstName = (GDataXMLElement *) [names objectAtIndex:0];
price = firstName.stringValue;
} else continue;
NSArray *names1 = [partyMember elementsForName:#"date"];
if (names1.count > 0) {
GDataXMLElement *firstName1 = (GDataXMLElement *) [names1 objectAtIndex:0];
date = firstName1.stringValue;
NSArray *names1 = [partyMember elementsForName:#"test"];
if (names1.count > 0) {
GDataXMLElement *firstName1 = (GDataXMLElement *) [names1 objectAtIndex:0];
test = firstName1.stringValue;

For the BOOL
A string is NO if its either nil or length 0. Otherwise its YES.
NSDateFormatter's dateFromString will convert strings to dates. You set it up with a c style formatter.
For the long use longValue as in long long myval = [mystring longLongValue];
NSString has several converters
– doubleValue
– floatValue
– intValue
– integerValue
– longLongValue
– boolValue
Use as required.

In the future, please first look at Apple's documentation. It is very thorough. In the page on NSString, you can see there is a boolValue method and a longLongValue method. You can read the specifics in the documentation, but those will handle your bool and long cases.
As for converting a date, there are many stackoverflow questions on that topic, this one here should answer your question.
I'm usually not one to say RTFM, but in this case the information was very easily found with a couple quick searches.

To convert NSString to BOOL use below method.
BOOL boolValue = [myString boolValue];
For converting to long use longLongValue: method of NSString.
For NSString to NSDate , use below as reference code.
NSString *dateString = #"2011-07-13";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];

NSString itself has functions to get bool and float values.
See reference.
To get date, u need to look at NSDateFormatter.

Related

how to use stringByTrimmingCharactersInSet in NSString

I have a string which gives the Date (below)
NSString*str1=[objDict objectForKey:#"date"];
NSLog(#" str values2%#",str1); --> 04-Jan-13
Now Problem is I need to Trim the"-13" from here .I know about NSDateFormatter to format date.but I can't do that here.I need to trim that
For that I am using:-
NSCharacterSet *charc=[NSCharacterSet characterSetWithCharactersInString:#"-13"];
[str1 stringByTrimmingCharactersInSet:charc];
But this does not work.this does not trim...how to do that..help
Not sure why not use an NSDateFormatter but here's a very specific way to approach this (very bad coding practice in my opinion):
NSString *theDate = str1;
NSArray *components = [theDate componentsSeparatedByString:#"-"];
NSString *trimmedDate = [NSString stringWithFormat:#"%#-%#",[components objectAtIndex:0],[components objectAtIndex:1]];
But this does not work.this does not trim...
It does trim, but since NSString is immutable, the trimmed string is thrown away, because you do not assign it to anything.
This would work (but do not do it like that!)
str1 = [str1 stringByTrimmingCharactersInSet:charc];
What you do is not trimming, it's taking a substring. NSString provides a much better method for that:
str1 = [str1 substringToIndex:6]; // Take the initial 6 characters
Something like this:
NSString *trimmed = [textStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
or this:
NSString *trimmed = [textStr stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"-13"];
what you have done is correct. Only thing is stringByTrimmingCharactersInSet returns NSString. So you need to assign this value to NSString, like
str1 = [str1 stringByTrimmingCharactersInSet:charc];
if you're sure you have your string always formatted like "NN-CCC-NN" you can just trim the first 6 chars:
NSString* stringToTrim = #"04-Jan-13";
NSString* trimmedString = [stringToTrim substringToIndex:6];
NSLog(#"trimmedString: %#", trimmedString); // -> trimmedString: 04-Jan

How to get integer values from nsstring Evalution in iPhone?

I have NSString like this #"0,0,0,0,0,0,1,2012-03-08,2012-03-17". I want values separated by comma. I want values before comma and neglect comma.
I am new in iPhone, I know how to do in Java but not getting how to do in Objective-C.
NSString *string = #"0,0,0,0,0,0,1,2012-03-08,2012-03-17";
NSArray *componentArray = [string componentSeperatedByString:#","];
Use the componentsSeparatedByString: method of NSString.
NSString *str = #"0,0,0,0,0,0,1,2012-03-08,2012-03-17";
NSArray *components = [str componentsSeparatedByString:#","];
for (NSString *comp in components)
{
NSLog(#"%#", comp);
}
for (NSString *s in [yourstring componentsSeparatedByString:#","])
{
int thisval = [s intValue];
}

How can I get an integer value from NSString in an iPhone application?

NSString * str=[zoneDict objectForKey:#"name"];
NSLog(#"==========string zone::==========%#",str);
// str="(GMT +3:00) Baghdad, Riyadh, Moscow, St. Petersbur";
How can I get the 3:00 value from the above string?
NSString *str = #"(GMT -3:00) Baghdad, Riyadh, Moscow, St. Petersbur";
NSRange endRange = [str rangeOfString:#")"];
NSString *timeString = [str substringWithRange:NSMakeRange(5, endRange.location-5)];
NSRange separatorRange = [timeString rangeOfString:#":"];
NSInteger hourInt = [[timeString substringWithRange:NSMakeRange(0, separatorRange.location)] intValue];
NSLog(#"Hour:%d",hourInt);
Rather than trying to extract the time offset from the string, is there any way you could store actual time zone data in your zoneDict? For example you could store NSTimeZone instances instead.
If all you have is the string, you could use an NSRegularExpression object and extract the relevant information using a regular expression instead.
If you could explain further what you're trying to do then there may be an alternative way to achieve what you want.
I like to use -[NSString componentsSeparatedByString]:
NSString *str = #"(GMT -3:00) Baghdad, Riyadh, Moscow, St. Petersbur";
NSArray *myWords = [myString componentsSeparatedByString:#")"];
NSString *temp1 = [myWords objectAtIndex:0];
if ([temp1 rangeOfString:#"-"].location == NSNotFound) {
NSArray *temp2 = [temp1 componentsSeparatedByString:#"+"];
NSString *temp3 = [temp2 objectAtIndex:1];
NSLog(#"Your String - %#", temp3);
}
else {
NSArray *temp2 = [temp1 componentsSeparatedByString:#"-"];
NSString *temp3 = [temp2 objectAtIndex:1];
NSLog(#"Your String - %#", temp3);
}
Output:
Your String - 3:00
Using regular expressions is the better option in my view (if you are forced to extract the '3' only). The regular expression string would contain something like "\d?" but don't quote me on that, you'll have to look up the exact string. Perhaps someone on here could provide the exact string.

Convert NSString to NSInteger?

I want to convert string data to NSInteger.
If the string is a human readable representation of a number, you can do this:
NSInteger myInt = [myString intValue];
[myString intValue] returns a cType "int"
[myString integerValue] returns a NSInteger.
In most cases I do find these simple functions by looking at apples class references, quickest way to get there is click [option] button and double-click on the class declarations (in this case NSString ).
I've found this to be the proper answer.
NSInteger myInt = [someString integerValue];
NSNumber *tempVal2=[[[NSNumberFormatter alloc] init] numberFromString:#"your text here"];
returns NULL if string or returns NSNumber
NSInteger intValue=[tempVal2 integerValue];
returns integer of NSNumber
this is safer than integerValue:
-(NSInteger)integerFromString:(NSString *)string
{
NSNumberFormatter *formatter=[[NSNumberFormatter alloc]init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *numberObj = [formatter numberFromString:string];
return [numberObj integerValue];
}
int myInt = [myString intValue];
NSLog(#"Display Int Value:%i",myInt);
NSString *string = [NSString stringWithFormat:#"%d", theinteger];

iPhone PList and NSDate issues

I am doing:
NSString *path = [[self class] pathForDocumentWithName:#"Alarms.plist"];
NSArray *alarmDicts = [NSMutableArray arrayWithContentsOfFile:path];
if (alarmDicts == nil)
{
NSLog(#"MER. Unable to read plist file: %#", path);
path = [[NSBundle mainBundle] pathForResource:#"Alarms"
ofType:#"plist"];
alarmDicts = [NSMutableArray arrayWithContentsOfFile:path];
}
_displayedObjects = [[NSMutableArray alloc]
initWithCapacity:[alarmDicts count]];
for (NSDictionary *currDict in alarmDicts)
{
Alarm *alarm = [[Alarm alloc] initWithDictionary:currDict];
[_displayedObjects addObject:alarm];
}
pathForDocumentWithName just a helper method, assume it works (it does). I add all of the values of the plist to an object, and store it in an array. Now if I do something like this:
NSUInteger index = [indexPath row];
id alarm = [[self displayedObjects] objectAtIndex:index];
NSString *title = [alarm title];
[[cell detailTextLabel] setText:title];
It works perfectly fine. But when trying to format the NSDate type in the plist file (listed as 'datetime')
NSDate *datetime = [alarm datetime];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"hh:mm"];
[[cell textLabel] setText:[formatter stringFromDate:datetime]];
It throws the NSLog for alarmDicts being nil, and returns nil for the string. I'm out of ideas, and have been trying for a few hours to solve this. Anyone have any ideas?
Also, if I print out the description for datetime, it works perfectly. Only nils and errors out when I attempt to use the NSDateFormatter on it.
A massive guess, but are you sure the dates in your property list are being read in as NSDate objects? If I were you, I'd check the type of your apparent NSDate objects, e.g.
NSLog(#"%#", [[alarm datetime] class]);
I would be suspicious that they're being loaded as NSStrings, which NSDateFormatter will decline to process — but they'll still appear to log correctly.
Unrelated comment: I'm sure it's a copy and paste error only, but you're leaking 'Alarm' objects at the bottom of your first snippet of code.