如何使用Core Data

如何使用Core Data,第1张

第一步:创建一个 DataDemo.xcdatamodel 文件,在其中建一个实体名字为 Entity1 ,实体中建两个字段 id 和 name。

第二步:为项目添加 CoreData.framework 框架,然后在 .pch 中加入 #import <coredata/coredata.h>

第三步:在 app delegate 中定义 core data 的相关对象(同时完成它们的初始化工作)

.h 文件:

#import <coredata/coredata.h>

@private

NSManagedObjectModel *managedObjectModel

NSManagedObjectContext *managedObjectContext

NSPersistentStoreCoordinator *persistentStoreCoordinator

@property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel

@property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext

@property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator

- (NSString*) applicationDocumentsDirectory

- (void) saveContext

.m 文件:

@synthesize managedObjectModel

@synthesize managedObjectContext

@synthesize persistentStoreCoordinator

- (void)dealloc {

[managedObjectModel release]

[managedObjectContext release]

[persistentStoreCoordinator release]

[super dealloc]

}

- (NSString*)applicationDocumentsDirectory

{

//return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)

NSString *basePath = ([paths count] >0) ? [paths objectAtIndex:0] : nil

return basePath

//return [NSURL URLWithString:basePath]

}

- (void)saveContext{

NSError *error = nil

NSManagedObjectContext *objectContext = self.managedObjectContext

if (objectContext != nil)

{

if ([objectContext hasChanges] &&![objectContext save:&error])

{

NSLog(@"Unresolved error %@, %@", error, [error userInfo])

abort()

}

}

}

- (NSManagedObjectContext *)managedObjectContext

{

if (managedObjectContext != nil) {

return managedObjectContext

}

NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]

if (coordinator != nil) {

managedObjectContext = [[NSManagedObjectContext alloc] init]

[managedObjectContext setPersistentStoreCoordinator:coordinator]

}

return managedObjectContext

}

- (NSManagedObjectModel *)managedObjectModel

{

if (managedObjectModel != nil) {

return managedObjectModel

}

//从本地所有 xcdatamodel 文件中获得这个 CoreData 的数据模板

managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain]

return managedObjectModel

}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator

{

if (persistentStoreCoordinator != nil) {

return persistentStoreCoordinator

}

//数据库名为TestDB.sqlite

NSURL *storeUrl = [NSURL fileURLWithPath:[[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"TestDB.sqlite"]]

NSError *error

persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]

if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nilURL:storeUrl options:nil error:&error]) {

NSAssert(0, @"persistentStoreCoordinator init failed!")

}

return persistentStoreCoordinator

}

- (void)applicationWillTerminate:(UIApplication *)application

{

NSError *error

if (managedObjectContext != nil) {

if ([managedObjectContext hasChanges] &&![managedObjectContext save:&error]) {

NSAssert(0, @"save changes failed when terminage application!")

}

}

}

第四步:在相关的 viewcontroller 中 *** 作数据,基本的 core data *** 作代码如下:

NSError *error

testSQLiteAppDelegate *app = (testSQLiteAppDelegate*)[[UIApplication sharedApplication] delegate]

NSManagedObjectContext *context = app.managedObjectContext

//1、插入

NSManagedObject *newManagedObject = nil

newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:@"Entity1" inManagedObjectContext:context]

[newManagedObject setValue:[NSNumber numberWithInt:1] forKey:@"id"]

[newManagedObject setValue:@"i love you" forKey:@"name"]

if (![context save:&error]){

NSLog (@"The error is: %@", [error userInfo])

}

else

{

NSLog (@"The newManagedObject's id is: %@", [newManagedObject valueForKey:@"id"])

}

//2、查询

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Entity1" inManagedObjectContext:context]

NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc] initWithKey:@"id" ascending:YES]

NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]

NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor1, sortDescriptor2, nil]

[fetchRequest setSortDescriptors:sortDescriptors]

[fetchRequest setEntity:entity]

[fetchRequest setFetchBatchSize:20]

NSArray *objects = [context executeFetchRequest: fetchRequest error:&error]

if (objects == nil)

{

NSLog(@"There was an error!")

}

else {

for (NSManagedObject *oneObject in objects)

{

NSLog(@"%@",[oneObject valueForKey:@"name"])

}

}

//3、删除

[context deleteObject:[objects objectAtIndex:0]]

if (![context save:&error]) {

exit(-1)

}

这里更详细的补充一点关于 core data 的 *** 作代码:

1、条件过滤:选择 cid=1 的数据

- (NSFetchedResultsController*) fetchedResultsController

{

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"cid=1"]

[fetchRequest setPredicate:predicate]

}

2、通用代码,在 viewcontroller 里面会用到:

TestViewController.h 的代码:

@interface TestViewController : UITableViewController <NSFetchedResultsControllerDelegate>

{

NSFetchedResultsController *fetchedResultsController

NSManagedObjectContext *managedObjectContext

}

@property (nonatomic, retain) NSFetchedResultsController *fetchedResultsController

@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext

- (void)configureCell:(UITableViewCell *)cell withCategory:(Category *)category

@end

TestViewController.m 的代码:

-(NSFetchedResultsController *)fetchedResultsController

{

if (fetchedResultsController != nil)

{

return fetchedResultsController

}

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Category" inManagedObjectContext:managedObjectContext]

[fetchRequest setEntity:entity]

NSSortDescriptor *nameDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]

NSArray *arraySortDescriptor = [[NSArray alloc] initWithObjects:nameDescriptor, nil]

[fetchRequest setSortDescriptors:arraySortDescriptor]

NSPredicate *predicate = [NSPredicate predicateWithFormat:cidString]

[fetchRequest setPredicate:predicate]

NSFetchedResultsController *frController = [[NSFetchedResultsController alloc]

initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:@"name" cacheName:@"Root"]

frController.delegate = self

self.fetchedResultsController = frController

[frController release]

[fetchRequest release]

[nameDescriptor release]

return fetchedResultsController

}

- (void)controllerWillChangeContent:(NSFetchedResultsController *)

{

[self.tableView beginUpdates]

}

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject

atIndexPath:(NSIndexPath *)indexPath forChangeType: (NSFetchedResultsChangeType)type

newIndexPath:(NSIndexPath *)newIndexPath

{

UITableView *tableView = self.tableView

switch (type) {

case NSFetchedResultsChangeInsert:

[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade]

break

case NSFetchedResultsChangeDelete:

[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]

break

case NSFetchedResultsChangeMove:

[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]

[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade]

break

case NSFetchedResultsChangeUpdate:

[self configureCell:[tableView cellForRowAtIndexPath:indexPath] withCategory:anObject]

break

default:

break

}

}

- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo

atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type

{

switch(type) {

case NSFetchedResultsChangeInsert:

[self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade]

break

case NSFetchedResultsChangeDelete:

[self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade]

break

}

}

- (void) controllerDidChangeContent:(NSFetchedResultsController *)controller

{

[self.tableView endUpdates]

}

第一种:通过人为的办法改变view.transform的属性

具体办法:

view.transform一般是View的旋转,拉伸移动等属性,类似view.layer.transform,区别在于 View.transform是二维的,也就是使用仿射的办法通常就是带有前缀CGAffineTransform的类(可以到api文档里面搜索这个前 缀的所有类),而view.layer.transform可以在3D模式下面的变化,通常使用的都是前缀为CATransform3D的类。

这里要记住一点,当你改变过一个view.transform属性或者view.layer.transform的时候需要恢复默认状态的话,记得先把他 们重置可以使用view.transform = CGAffineTransformIdentity,或者view.layer.transform = CATransform3DIdentity,假设你一直不断的改变一个view.transform的属性,而每次改变之前没有重置的话,你会发现后来 的改变和你想要的发生变化了,不是你真正想要的结果。

好了,上面介绍了旋转的属性,接下来就是关键了。官方提供了一个办法就是查看当前电池条的状态UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation通过这个办法,你可以知道当前屏幕的电池条的显示方向,而且你还可以 强制设置他的显示方向,通过设置这个属性就OK了,可以选择是否动画改变电池条方向。有了这两个那我们就可以任意的改变我们想要的显示方式了。

1.获取当前电池条的方向UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation

2.获取当前屏幕的大小CGRect frame = [UIScreen mainScreen].applicationFrame

3.设置我们的View的中心点

CGPoint center = CGPointMake(frame.origin.x + ceil(frame.size.width/2), frame.origin.y + ceil(frame.size.height/2))

4.根据当前电池条的方向,获取需要旋转的角度的大小。通常

if (orientation == UIInterfaceOrientationLandscapeLeft) {

return CGAffineTransformMakeRotation(M_PI*1.5)

} else if (orientation == UIInterfaceOrientationLandscapeRight) {

return CGAffineTransformMakeRotation(M_PI/2)

} else if (orientation == UIInterfaceOrientationPortraitUpsideDown) {

return CGAffineTransformMakeRotation(-M_PI)

} else {

return CGAffineTransformIdentity

}

5.可以动画的改变我们view的显示方式了

[[UIApplication sharedApplication] setStatusBarOrientation:UIDeviceOrientationLandscapeRight animated:YES]

CGFloat duration = [UIApplication sharedApplication].statusBarOrientationAnimationDuration(获取当前电池条动画改变的时间)

[UIView beginAnimations:nil context:nil]

[UIView setAnimationDuration:duration]

//在这里设置view.transform需要匹配的旋转角度的大小就可以了。

[UIView commitAnimations]

第二种:通过setOrientation:的办法强制性的旋转到一个特定的方向。

注意:apple在3.0以后都不支持这个办法了,这个办法已经成为了私有的了,但是要跳过App Stroe的审核,需要一点巧妙的办法。

不要直接调用[[UIDevice currentDevice] setOrientation: UIInterfaceOrientationLandscapeRight]这样的办法来强制性的横屏,这样导致你的程序是很难通过App Store审核的。但是你可以选择使用performSelector的办法来调用它。具体就几行代码如下:

//强制横屏

if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {

[[UIDevice currentDevice] performSelector:@selector(setOrientation:)

withObject:(id)UIInterfaceOrientationLandscapeRight]

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/bake/11374671.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-15
下一篇 2023-05-15

发表评论

登录后才能评论

评论列表(0条)

保存