简体   繁体   中英

How To Match NSUserDefaults and CoreData Attribute and Get Data if both are same

Here i have an entity named ClipTable i am fetching all clip related information of all users here but i want to fetch clip information with particular user who is logged in,for that i have stored his user_id using NSUserDefaults. And my clip table has a attribute named created_by_user, which is basically a userid of a particular user who stores the clip. So using this created_by_user attribute and user_id from NSUserDefaults i want to check whether both are same. And if both are same get the clip record of that particular user only. below is the code with which i am only able to show all the clip record of all the user in tableView using NSFetchResultController. But now i want to get records for the particular user only. Hard time doing this. Any help is appreciated.

user_id is [NSUserDefaults standardUserDefaults] stringForKey:@"userID"]

-(void)fetch:(NSString*)catgeory :(BOOL)All{

AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
self.managedObjectContext = delegate.managedObjectContext;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"ClipTable"];

// Add Sort Descriptors
[fetchRequest setSortDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"modifieddate" ascending:NO]]];

//_fetchedResultsController=nil;
// Initialize Fetched Results Controller
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];

if (All==NO) {
    [fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"(page_categorisation == %@)",catgeory]];
}

[fetchRequest setFetchBatchSize:0];
//  [fetchRequest setFetchLimit:10];
// Configure Fetched Results Controller
[self.fetchedResultsController setDelegate:self];

// Perform Fetch
NSError *error = nil;
[self.fetchedResultsController performFetch:&error];

if (error) {
    NSLog(@"Unable to perform fetch.");
    NSLog(@"%@, %@", error, error.localizedDescription);
}
}

Here is the simple solution just use predicate to fetch the clips of logged in user. Get the value of current logged in user from NSUserDefaults in currentLoggedInUser and pass it below.

NSString *predicateFrmt = @"created_by_user == %@ ;
NSPredicate *predicate = [NSPredicate predicateWithFormat: predicateFrmt, currentLoggedInUser];
fetchRequest.predicate = predicate;

for Category you can use AND

[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"(page_categorisation == %@ AND created_by_user == %@ )",catgeory,currentLoggedInUser]];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM