我是新手NSManagedObjectContext
。我Link
在我的应用程序中创建了一个实体,其中包含一个NSString *url
.
在我的应用程序的某个时刻,我需要Link
在我的基础中插入一个新的,所以我只需这样做:
Link *link = [NSEntityDescription
insertNewObjectForEntityForName:@"Link"
inManagedObjectContext:self.managedObjectContext];
link.url = myUrl;
但在此之前,我想检查我的基地中是否还没有具有相同 url 的链接。而且我不知道该怎么做……我该怎么办?
编辑:从我在网上找到的工具中使用此方法从基础检索数据:
// Fetch objects with a predicate
+(NSMutableArray *)searchObjectsForEntity:(NSString*)entityName withPredicate:(NSPredicate *)predicate andSortKey:(NSString*)sortKey andSortAscending:(BOOL)sortAscending andContext:(NSManagedObjectContext *)managedObjectContext
{
// Create fetch request
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
// If a predicate was specified then use it in the request
if (predicate != nil)
[request setPredicate:predicate];
// If a sort key was passed then use it in the request
if (sortKey != nil) {
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sortKey ascending:sortAscending];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
}
// Execute the fetch request
NSError *error = nil;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
// If the returned array was nil then there was an error
if (mutableFetchResults == nil)
NSLog(@"Couldn't get objects for entity %@", entityName);
// Return the results
return mutableFetchResults;
}
我想知道如何使用它。
谢谢你的帮助。