Pages

Showing posts with label NSMutable Array. Show all posts
Showing posts with label NSMutable Array. Show all posts

Thursday, September 12, 2013

Random Number Array in Objective C

Hi, i think this is a common and basic requirement for every developer in each field, to get the Random numbers in Array. I have made a function to simplify this logic in Objective C.
So here is the code if this
-(void) checkExistance:(int) max
{
    int value = [self randomNumberFrom:0 to:max];//Modify according to minimum /maximum value in Array
    int i = 0;
    for (i = 0; i < [self.numbers count]; i++)
        if ([[self.numbers objectAtIndex:i] integerValue] == value)
            break;
    
    if (i == [self.numbers count])
        [self.numbers addObject:[NSNumber numberWithInt:value]];
    if ([self.numbers count] != max)
        [self checkExistance:max];
}
- (int) randomNumberFrom: (int) minValue to: (int) maxValue
{
    int rangeValue = maxValue - minValue;
    return (arc4random() % rangeValue) + minValue;

}

You just need to call checkExistance method with passing a maximum value in this. You can modify your code for minimum and maximum as well in this. 

Now just call

[self checkExistance:6];

and you will see the result by following

for(int j = 0;j<self.numbers.count;j++)
{
    NSLog(@" %@", [self.numbers objectAtIndex:j]);

}

Wednesday, January 23, 2013

How to work with NSMutable Array and For Loop in xCode

first declare the Mutable Array in filename.h



#import <Foundation/Foundation.h>

@interface FileNameAsClassName: NSObject
{
    NSMutableArray *users;
}
@property(nonatomic,strong) NSMutableArray *users;
@end;

Now define this users array in filename.m


#import "FileNameAsClassName.h"

@implementation FileNameAsClassName
@synthesize users;

Now use this to add Objects in any function, where you required, after initialize

//Initializing
users = [[NSMutableArray alloc] init];

//Inserting Objects in some function, where required
[users addObject:someObjectName];


Now use this as below in required function 


for(int i=0;i<users.count;i++)
{
    someObjectName = [users objectAtIndex:i];
    //Now use someObjectName as Obejct, which you have inserted
}