Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add null or nil value in "dynamic NSArray" in Objective-C

I am facing a problem regarding to add Null or nil value in NSArray. Actually I am adding Null value because my array count is not same. I am adding three array in Custom TableViewCell two array are from webservice and one array is from database. I am saving IndexPath in core data and then retrieving it.

enter image description here

As shown in Image I am saving indexPath in String and convert it in NSInteger from DidSelectAtIndexPath and show it in cellForRowAtIndexPath. My problem is, it's getting override because it is stored in string. So that I save it in coredataa and retrieve it but I get problem for mismatch count of array in cellforrowatindexpath. My code is like this

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
         static NSString *STI=@"STI";
        AuditTableViewCell *cell = (AuditTableViewCell *)[tableView dequeueReusableHeaderFooterViewWithIdentifier:STI];
        if (cell == nil)
        {
            NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"AuditTableViewCell" owner:self options:nil];
            cell = [nib objectAtIndex:0];
            cell.accessoryType=UITableViewCellAccessoryNone;
        }
        cell.audittitlelbl.text=[NSString stringWithFormat:@"%@",[idarray objectAtIndex:indexPath.row]];
        cell.auditdesclbl.text=[NSString stringWithFormat:@"%@",[namearray objectAtIndex:indexPath.row]];

        NSManagedObject *device2 = [devices objectAtIndex:indexPath.row];
        NSMutableArray *Checkarray=[devices valueForKey:@"Key"]; // Hear in this array I am getting Index count problem
        NSLog(@"Device =%@",device2);
        NSLog(@"Check Array =%@",Checkarray);
        if(indexPath.row == CurrentIndexPath)
        {
            cell.listlbl.text=GlobalString;
            [cell setBackgroundColor:[UIColor greenColor]];
        }

        return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
           CurrentIndexPath=indexPath.row;
            NSLog(@"Current Index Path =%ld",(long)CurrentIndexPath);
            GlobalIndexPath = [[NSString stringWithFormat: @"%ld", (long)CurrentIndexPath] mutableCopy];

            NSManagedObjectContext *context = [self managedObjectContext];

            if (self.device) {
                // Update existing device
                [device setValue:GlobalStringChk forKey:@"Key1"];
                [device setValue:GlobalIndexPath forKey:@"Key"];


            } else {
                // Create a new device
                NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:@"Device" inManagedObjectContext:context];
                [newDevice setValue:GlobalStringChk forKey:@"Key1"];
                [newDevice setValue:GlobalIndexPath forKey:@"Key"];
            }

            NSError *error = nil;
            // Save the object to persistent store
            if (![context save:&error]) {
                NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
            }



            [Audittable reloadData];



            NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
            NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Device"];
            self.devices = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
}

This is my code hear I am saving indexpath in coredata and retrieving it in array. I have a problem for count of array in cellforrowatindexpath. How can I add Null or nil value in array so that it count get same. My Array is a dynamic array.The main problem is that I need to change the colour of cell if user click on it.when I store the value in NSInteger and convert it into indexpath I can change the colour But only for one cell at a time.When I click on other cell integer value get override. So for that I save it to core data and retrive but when I fetch core data array in cellforrowatindexpath it crash because of different count .Thanks in Advance!

like image 791
Muju Avatar asked Dec 09 '16 06:12

Muju


People also ask

Can NSArray contain nil?

arrays can't contain nil. There is a special object, NSNull ( [NSNull null] ), that serves as a placeholder for nil.

How do you declare NSArray in Objective-C?

Creating NSArray Objects Using Array Literals In addition to the provided initializers, such as initWithObjects: , you can create an NSArray object using an array literal. In Objective-C, the compiler generates code that makes an underlying call to the init(objects:count:) method.

What is null in Objective-C?

C represents nothing as 0 for primitive values and NULL for pointers (which is equivalent to 0 in a pointer context). The only time you see NULL in Objective-C code is when interacting with low-level C APIs like Core Foundation or Core Graphics.


2 Answers

We cannot add nil directly inside a collection like NSMutableArray as it will raise an exception. If at all it is required to add nil inside collections like NSMutableArray, we can do so by using a singleton class NSNull.

For instance, we have a array of type NSMutableArray, we can add nil using NSNull as-

[array addObject:@"string"];
[array addObject:[NSNull null]];

... and so on...

The NSNull class defines a singleton object used to represent null values in collection objects (which don’t allow nil values).

like image 157
Sanjay Mohnani Avatar answered Oct 07 '22 00:10

Sanjay Mohnani


First you can't add elemets in NSArray, you must use NSMutableArray instead. Second thing you can not add nil in your NSMutableArray.

So, you should add empty string instead of nil something like,

NSMutableArray *arr = [[NSMutableArray alloc]init];

[arr addObject:@""];

or you can add NSNull Object like,

[arr addObject:[NSNull null]];

And you can check that string is empty or not when want to display in UI something like(if added empty string),

NSString *tempStr = [arr objectAtIndex:0];

if (tempStr.length > 0) {

    NSLog(@"string is not empty.");
}
else{

    NSLog(@"Sring is empty");
}
like image 29
Ketan Parmar Avatar answered Oct 07 '22 02:10

Ketan Parmar