开发者

How to convert NSArray to integer values

开发者 https://www.devze.com 2023-02-08 17:04 出处:网络
In my iPhone by applying below code I am able to get value of \"i\" NSMutableArray *Array = [NSMutableArray arrayWithCapacity:100];

In my iPhone by applying below code I am able to get value of "i"

NSMutableArray *Array = [NSMutableArray arrayWithCapacity:100];

for (NSUInteger i = 0; i < 10; i++) {          
    id a = [NSDecimalNumber numberWithDouble:i];
    [Array addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:a, @"a", nil]];
 }

But if I want to get value from array like as an example

NSArray * numberArray = [[NSArray alloc] initWithObjects:@"0.1",@"0.2",@"0.5",nil];

and then if I want to use it as

NSMutableArray *Array = [NSMutableArray arrayWithCapacity:100];

for (NSUInteger i = 0; i < 10; i++) {  开发者_开发知识库        
    id a = [NSDecimalNumber numberWithDouble:[numberArray objectAtIndex:i]];
    [Array addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:a, @"a", nil]];
 }

How can I do this?


I don't really understand but I'll try to help you.

If you want to store Integers into a NSArray use this code to set and get them :

// Set
NSArray *yourArray = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:2], [NSNumber numberWithInt:3],nil];

// Get
int currentNumber;
for(int i=0; i<[yourArray count]; i++)
{
    currentNumber = [((NSNumber*)[yourArray objectAtIndex:i]) intValue];
}


So you start with this array, whose content is made of NSString objects (@"0.1" is a string):

NSArray * numberArray = [[NSArray alloc] initWithObjects:@"0.1",@"0.2",@"0.5",nil];

the you can scan each element using this loop:

for(NSString *strNum in numberArray) {
  float number = [strNum floatValue];
  NSLog(@"Number: %f",float);
}

the string to float conversion is possible thanks to the floatValue() method of NSString.

You can use doubleValue, longLongValue, integerValue for other types. These methods will return 0 if no valid number representation is given with the string.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号