How to check if NSString is numeric or not [duplicate] - objective-c

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
iphone how to check that a string is numeric only
I have one NSString, then i want check the string is number or not.
I mean
NSString *val = #"5555" ;
if(val isNumber ){
return true;
}else{
retun false;
}
How can I do this in Objective C?

Use [NSNumberFormatter numberFromString: s]. It returns nil if the specified string is non-numeric. You can configure the NSNumberFormatter to define "numeric" for your particular scenario.
#import <Foundation/Foundation.h>
int
main(int argc, char* argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSLocale *l_en = [[NSLocale alloc] initWithLocaleIdentifier: #"en_US"];
NSLocale *l_de = [[NSLocale alloc] initWithLocaleIdentifier: #"de_DE"];
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
[f setLocale: l_en];
NSLog(#"returned: %#", [f numberFromString: #"1.234"]);
[f setAllowsFloats: NO];
NSLog(#"returned: %#", [f numberFromString: #"1.234"]);
[f setAllowsFloats: YES];
NSLog(#"returned: %#", [f numberFromString: #"1,234"]);
[f setLocale: l_de];
NSLog(#"returned: %#", [f numberFromString: #"1,234"]);
[l_en release];
[l_de release];
[f release];
[pool release];
}

You could use rangeOfCharacterFromSet::
#interface NSString (isNumber)
-(BOOL)isInteger;
#end
#interface _IsNumber
+(void)initialize;
+(void)ensureInitialization;
#end
#implementation NSString (isNumber)
static NSCharacterSet* nonDigits;
-(BOOL)isInteger {
/* bit of a hack to ensure nonDigits is initialized. Could also
make nonDigits a _IsNumber class variable, rather than an
NSString class variable.
*/
[_IsNumber ensureInitialization];
NSRange nond = [self rangeOfCharacterFromSet:nonDigits];
if (NSNotFound == nond.location) {
return YES;
} else {
return NO;
}
}
#end
#implementation _IsNumber
+(void)initialize {
NSLog(#"_IsNumber +initialize\n");
nonDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
}
+(void)ensureInitialization {}
#end

Related

Why does NSMutablearray keep returning null?

I am generating a random equation say like 2*3+4..... and using DDMathparser to evaluate it. Here I have a class method which is supposed to return a random equation(stored inside a mutable array) only if it evaluates to a integer.
however it keeps returning Null and i can't figure out why. Please help me out.!
#import "Equation.h"
#import "DDMathParser.h"
#implementation Equation
-(NSMutableArray*)randEquation{
NSMutableArray* usableEquation=[[NSMutableArray alloc]init];
while(1){
NSArray *nums = #[#"1", #"2", #"3", #"4", #"5",#"6",#"7",#"8",#"9"];
unsigned index1=arc4random()%9;
NSString* num = [NSString stringWithFormat:#"%#", [nums objectAtIndex:index1]];
NSArray *symbols = #[#"+", #"-", #"*", #"/"];
unsigned index=arc4random()%4;
NSString* symb = [NSString stringWithFormat:#"%#", [symbols objectAtIndex:index]];
NSMutableArray *arrayOfSymbolsAndNumbers = [[NSMutableArray alloc] init];
for( int i=0;i<=10;i++){
if (i%2==0) {
[arrayOfSymbolsAndNumbers addObject:num];
}
else{
[arrayOfSymbolsAndNumbers addObject:symb];
}
}
NSMutableString *stringOfSymbolsAndNumbers=[[NSMutableString alloc]init];
for (NSObject * obj in arrayOfSymbolsAndNumbers)
{
[stringOfSymbolsAndNumbers appendString:[obj description]];
}
usableEquation=arrayOfSymbolsAndNumbers;
NSNumber *result=[stringOfSymbolsAndNumbers numberByEvaluatingString];
float resultFloat = [result floatValue];
float checker=resultFloat;
if (floor(checker)==checker) {
break;
}
else{
continue;
}
}
return usableEquation;
}
#end
NSLog(#"The content of array is%#",[equation randEquation]);
Based on your code, for this log to output The content of array is(null) means that equation is nil. Your randEquation (while not efficient) looks ok, the problem is that you haven't created the equation instance when you run the log statement.

ObjC : NSLog a pointer name

I filled a NSMutableArray with 3 class instances I created. Now I want to iterate this array to get some variable values. I'm able to do so, but not able to print my instance name (bread, water, ...) Instead, I get their addresses.
I guess it's simple but I'm struggling a bit, so if someone knows how to ...
Thank you
#import <Foundation/Foundation.h>
#import "StockHolding.h";
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
StockHolding *bread = [[StockHolding alloc] init];
[bread setPurchaseSharePrice:100];
[bread setCurrentSharePrice:120];
[bread setNumberOfShares:100];
StockHolding *water = [[StockHolding alloc] init];
[water setPurchaseSharePrice:100];
[water setCurrentSharePrice:80];
[water setNumberOfShares:10];
StockHolding *tomatoes = [[StockHolding alloc] init];
[tomatoes setPurchaseSharePrice:100];
[tomatoes setCurrentSharePrice:50];
[tomatoes setNumberOfShares:1];
NSMutableArray *myStock = [NSMutableArray arrayWithObjects:bread, water, tomatoes, nil];
for (StockHolding *s in myStock)
{
NSLog(#"Here is what I paid for my %p : %f", s, [s costInDollars]);
NSLog(#"Here is what I earn for my %p : %f", s, [s valueInDollars]);
}
[pool drain];
return 0;
}
Why not implement the -(NSString *)description method on your StockHolding class? Then you can use %# in string formats and it will output the description there.
Alternatively you can also output any other string property of StockHolding instances with %#.
If you want to NSLog an object and it's pointer name you can add this #define in your preprocessor macro #define OLog(x) NSLog(#"%s = %#",#x, x);

NSString addition what does this Objective-c code do?

Ran across this NSString Addition and I hav no idea what it does or is used for?
NSString *NSStringWithFormat(NSString *formatString, ...) {
va_list args;
va_start(args, formatString);
NSString *string = [[NSString alloc] initWithFormat:formatString arguments:args];
va_end(args);
#if defined(__has_feature) && __has_feature(objc_arc)
return string;
#else
return [string autorelease];
#endif
}
It's a C function that lets you do this:
NSString *str = NSStringWithFormat(#"This is a number: %d", someIntValue);
instead of this:
// No ARC
NSString *str = [NSString stringWithFormat:#"This is a number: %d", someIntValue];
or
// With ARC
NSString *str = [[NSString alloc] initWithFormat:#"This is a number: %d", someIntValue];
Seems kind of pointless to me since with or without ARC you can use the "No ARC" code. This C function only saves a few characters.

iOS - object sent autorelease too many times

I have a method that is reading some information from a sqlite db and initialising a class called Achievement. When I analyse this code I am given the feedback 'object sent autorelease too many times'. I don't really understand where I am going wrong - why is the retval object released on line 225 and not at the return statement on line 229?
Can someone please explain where I have made a mistake in the code below and how I can fix it?
Function Code (so answerer can easily copy/paste):
- (Achievement *)getAchievement:(int)Id
{
Achievement *retval = [[Achievement alloc] autorelease];
NSString *query = [NSString stringWithFormat:#"SELECT * FROM Achievements where ID = %d", Id];
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(_database, [query UTF8String], -1, &statement, nil)
== SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW) {
int Id = sqlite3_column_int(statement, 0);
char *name = (char *) sqlite3_column_text(statement, 1);
char *title = (char *) sqlite3_column_text(statement, 2);
char *description = (char *) sqlite3_column_text(statement, 3);
Boolean Achieved;
char *com = (char *) sqlite3_column_text(statement, 4);
NSString *c1 = [[[NSString alloc] initWithUTF8String:com] autorelease];
Achieved = [c1 isEqualToString:#"1"];
NSDate *CompletedDate = (NSDate *) sqlite3_column_text(statement, 5);
char *icon = (char *) sqlite3_column_text(statement, 6);
int New = sqlite3_column_int(statement, 7);
NSString *Title = [[[NSString alloc] initWithUTF8String:title] autorelease];
NSString *Description = [[[NSString alloc] initWithUTF8String:description] autorelease];
NSString *Name = [[[NSString alloc] initWithUTF8String:name] autorelease];
NSString *Icon = [[[NSString alloc] initWithUTF8String:icon] autorelease];
retval = [retval initDetails:Id :Name :Title: Description : Achieved : CompletedDate: Icon: New];
}
sqlite3_finalize(statement);
}
return retval;
}
Analysis feedback image:
As always any feedback is greatly appreciated.
Achievement *retval = [[Achievement alloc] autorelease];
this is very bad idea to do that. You ALWAYS have to initialize object before using it.
Instead you're initializing it in a loop:
retval = [retval initDetails:Id :Name :Title: Description : Achieved : CompletedDate: Icon: New];
I don't really get why you need to initialize the same object multiple times. Maybe, you need to create multiple objects and init them with different values?
Rearrange this:
Achievement *retval = nil;
while (...) {
[retval release];
retval = [[Achievement alloc] initDetails: ...];
}
return [retval autorelease];
I guess you're confusing the compiler with the wrong sequence of alloc, init, autorelease. What you should be doing instead is the following (pseudocode):
Achievement *retval = nil;
while (...) {
retval = [[[Achievement alloc] initDetails: ...] autorelease];
}
return retval;

How do I retrieve all the rows from an SQLite table?

hello guys i am doing some database operations in iphone .. please can anyone explain me how to retrieve all rows from the table..here in this example it retreives only the latest entered data..
while(sqlite3_step(statement) == SQLITE_ROW)
{
char *field1 = (char *) sqlite3_column_text(statement,0);
NSString *field1Str = [[NSString alloc] initWithUTF8String: field1];
char *field2 = (char *) sqlite3_column_text(statement,1);
NSString *field2Str = [[NSString alloc] initWithUTF8String: field2];
NSString *str = [[NSString alloc] initWithFormat:#"%#::%#",field1Str, field2Str];
textv.text=str;
[field1Str release];
[field2Str release];
}
You were doing all right so far. Just keep adding the final formatted string (str) in an NSMutableArray and finally return it from the function.
// Take an array to store all string.
NSMutableArray *allRows = [[[NSMutableArray alloc] init] autorelease];
while(sqlite3_step(statement) == SQLITE_ROW)
{
char *field1 = (char *) sqlite3_column_text(statement,0);
NSString *field1Str = [[NSString alloc] initWithUTF8String: field1];
char *field2 = (char *) sqlite3_column_text(statement,1);
NSString *field2Str = [[NSString alloc] initWithUTF8String: field2];
NSString *str = [NSString stringWithFormat:#"%#::%#",field1Str, field2Str];
// textv.text=str; // I don't know why your are mixing your view controller stuff's in database function.
// Add the string in the array.
allRows addObject:str];
[field1Str release];
[field2Str release];
}
// Finally you can return your allRows
return allRows;