Search code examples
iosobjective-cfor-loopnsarraynsdate

How to add loop in my code


I have NSMutableArray *arrList and I founded Monday objects in MutableArray *arrList. But now is static written in if condition, Look like in my code:(if ([str containsString:@"Monday"])). I want a array load place to static Monday. That mean loop wise one by one week day load in static Monday.

NSArray*loopAry = [[NSArray alloc]initWithObjects:@"Sunday",@"Monday",@"Tuesday",nil];

That is loopAry objects one by one reload to place Static Monday.

This helps to get dynamic code and reload only array in loop and get weekdays data

NSMutableArray *arrList = [[NSMutableArray alloc]initWithObjects:@"25-11-2016, Friday",
   @"26-11-2016, Saturday",
   @"27-11-2016, Sunday",
   @"28-11-2016, Monday",
   @"29-11-2016, Tuesday",
   @"30-11-2016, Wednesday",
   @"01-12-2016, Thursday",
   @"02-12-2016, Friday",
   @"03-12-2016, Saturday",
   @"04-12-2016, Sunday",
   @"05-12-2016, Monday",
   @"06-12-2016, Tuesday",
   @"07-12-2016, Wednesday", nil];

NSMutableArray *result = [[NSMutableArray alloc]init];
for (id element in  arrList){
NSString *str = element;
    if ([str containsString:@"Monday"]) {
        [result addObject:element];
    }
}

// print result
NSLog(@"%@",result);
 (
"28-11-2016, Monday",
"05-12-2016, Monday"
)

Solution

  • You can get Array of provided day like below :

    NSArray *loopAry = [[NSArray alloc]initWithObjects:@"Sunday",@"Monday",@"Tuesday",nil];
    
    NSMutableArray *arrList = [[NSMutableArray alloc]initWithObjects:@"25-11-2016, Friday",
                                   @"26-11-2016, Saturday",
                                   @"27-11-2016, Sunday",
                                   @"28-11-2016, Monday",
                                   @"29-11-2016, Tuesday",
                                   @"30-11-2016, Wednesday",
                                   @"01-12-2016, Thursday",
                                   @"02-12-2016, Friday",
                                   @"03-12-2016, Saturday",
                                   @"04-12-2016, Sunday",
                                   @"05-12-2016, Monday",
                                   @"06-12-2016, Tuesday",
                                   @"07-12-2016, Wednesday", nil];
    
    NSMutableArray *result = [[NSMutableArray alloc]init];
    for (NSString *strData in  arrList){
        //2nd Loop for your weekdays array.By this you will get weekdays array in result.
        for (NSString *strDay in loopAry) {
            if ([strData containsString:strDay]) {
                  [result addObject:strData];
            }
        }
    
    }
    
    // print result
    NSLog(@"%@",result);
    

    Hope this will help you to get week days.