Check If Property Is Set in Core Data

Check if property is set in Core Data?

Update for Xcode 7: This issue has been solved with Xcode 7 beta 2.
Optional Core Data properties are now defined as optional properties
in the managed object subclasses generated by Xcode. It is no longer
necessary to edit the generated class definition.


(Previous answer:)

When creating the NSManagedObject subclasses, Xcode does not define optional properties for those attributes which are marked as "optional" in the Core Data model inspector.
This looks like a bug to me.

As a workaround, you can cast the property to
an optional (as String? in your case) and then test it with optional binding

if let notice = someManagedObject.noticeText as String? {
println(notice)
} else {
// property not set
}

In your case that would be

if let notice = formQuestions[indexPath.row].noticeText as String? {
println(notice)
} else {
// property not set
}

Update: As of Xcode 6.2, this solution does not work anymore
and crashes with a EXC_BAD_ACCESS runtime exception
(compare Swift: detecting an unexpected nil value in a non-optional at runtime: casting as optional fails)

The "Old answer" solution below still works.


(Old answer:)

As @Daij-Djan already stated in a comment, you have to define the property for an
optional Core Data attribute as optional or implicitly unwrapped optional:

@NSManaged var noticeText: String? // optional
@NSManaged var noticeText: String! // implicitly unwrapped optional

Unfortunately, Xcode does not define the optional properties correctly when creating
the NSManagedObject subclasses, which means that you have to re-apply the changes
if you create the subclasses again after a model change.

Also this seems to be still undocumented, but both variants worked in my test case.

You can test the property with == nil:

if formQuestions[indexPath.row].noticeText == nil {
// property not set
}

or with an optional assignment:

if let notice = formQuestions[indexPath.row].noticeText {
println(notice)
} else {
// property not set
}

CoreData / NSManagedObject mapping, how to check if the object property supports the passed type

This is the purpose of NSAttributeDescription that you can get to via the propertiesByName of the NSEntityDescription for the entity. It will tell you the attributeType that you can use for validation / comparison. See also attributeValueClassName which you may be able to leverage.

Faster way to check if entry exists in Core Data

Whether fetching the instance or getting the count, you're still doing one fetch request per incoming record. That's going to be slow, and your code will be spending almost all of its time performing fetches.

One improvement is to batch up the records to reduce the number of fetches. Get multiple record IDs into an array, and then fetch all of them at once with a predicate like

NSPredicate(format: "inputId IN %@", inputIdArray)

Then go through the results of the fetch to see which IDs were found. Accumulate 50 or 100 IDs in the array, and you'll reduce the number of fetches by 50x or 100x.

Deleting all the entries for the timestamp and then re-inserting them might be good, but it's hard to predict. You'll have to insert all 20,000. Is that faster or slower than reducing the number of fetches? It's impossible to say for sure.

How to check if a relationship has been established - Core Data

Assuming that the entities are defined as in Core Data Detail View with relationship, the following code establishes a relationship between
the two objects:

[routineEntityDetail setValue:routineEntity forKey:@"routineinfo"];

It sets the relationship pointer from routineEntityDetail to routineEntity.

Since routinedet is the inverse relationship to routineinfo, routineEntityDetail
is automatically added to the routinedet relationship of routineEntity.

This does not make sense:

[[routineEntityDetail valueForKey:@"name"] addObject:routineEntity];

And this looks OK:

[routineEntity setValue: info.name  forKey:@"routinename"];
[routineEntityDetail setValue: info.details.muscle forKey:@"image"];

Swift: How to check a core data NSSet for an object

Swift also has these elegant methods. ;) Just use the same method in swift as you did in objective-c:

var existingRecord = self.employeeRecord.absences.valueForKey("id").containsObject(myId)

Fastest way to check if an object exists in Core Data or not?

Setup a Core Data request and, instead of actually issuing the query, do the following:

NSError *error = nil;
NSUInteger count = [managedObjectContext countForFetchRequest:request
error:&error];
if (!error) {
return count;
} else {
return 0;
}

In practice, the method countForFetchRequest:error: returns the number of objects a given fetch request would have returned if it had been passed to executeFetchRequest:error:.


Edit: (by Regexident)

As Josh Caswell correctly commented, the correct way to handle errors is either this:

if (count == NSNotFound) {
NSLog(@"Error: %@", error);
return 0;
}
return count;

or this (without error logging):

return (count != NSNotFound) ? count : 0;

Check if name attribute already exists in CoreData

You can use a fetch request with a predicate to find objects matching certain attributes.
If you are only interested in the existence
of an object with the given key, use countForFetchRequest instead of actually fetching the objects, and limit the result set to one object:

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"BankInfo"];
[request setPredicate:[NSPredicate predicateWithFormat:@"name = %@", theName]];
[request setFetchLimit:1];
NSUInteger count = [context countForFetchRequest:request error:&error];
if (count == NSNotFound)
// some error occurred
else if (count == 0)
// no matching object
else
// at least one matching object exists


Related Topics



Leave a reply



Submit