I made a weird bug in my app and I am at a loss on why it is behaving this way. If there are more than 0 objects in the entity, it will display the correct amount. If there are 0 objects in the entity, it will display 1, not 0 (even though it works fine in another fetch request).
Note: The "cell.badgeString" is nothing special, it just displays the count of the objects in the entity by the disclosure indicator.
if (cell.tag == 0)
{
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Uploads" inManagedObjectContext:self.managedObjectContext];
[request setEntity:entity];
[request setIncludesSubentities:NO];
NSArray *results = [self.managedObjectContext executeFetchRequest:request error:nil];
NSArray *resultString = [results valueForKey:@"url"];
NSString *string = [resultString description];
// I'm thinking it has something to do with this right here, maybe that is why it is displaying one instead of zero?
NSArray *count = [string componentsSeparatedByString:@","];
NSString *upload_amount = [[NSNumber numberWithInteger:count.count] stringValue];
cell.badgeString = upload_amount;
}
I can't just do [self.managedContext countForFetchRequest], as I have a group of URLs stored in a string in Core Data, and I have to separate them first to get the correct amount.
Thanks for any help.
Your code is very confusing, mainly because you are using strange variable names. For example, the resultString
is an NSArray
. Another array you call count
. The description of an array would start and end with brackets, so this is certainly not what you intend.
So here is what happens in your code if you have zero results
NSArray *results = [self.managedObjectContext executeFetchRequest:request error:nil];
// results is () - an empty array
NSArray *resultString = [results valueForKey:@"url"];
// resultString is () - an empty array
NSString *string = [resultString description];
// string contains "()" or something like that
NSArray *count = [string componentsSeparatedByString:@","];
// count contains ( "()" ) - an array with one string
count.count
is 1
and the stringValue
of that is @"1"
.
To solve this, you could check results.count
first and react accordingly if it is 0.