MagicalRecord简单使用小记

一般采用pod安装,导入框架
#import <CoreData+MagicalRecord.h>



- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // 其他代码操作......

    [MagicalRecord setupCoreDataStack];

    // 其他代码操作......
}

- (void)applicationWillTerminate:(UIApplication *)application {

     // 其他代码操作......

      [MagicalRecord cleanUp];

     // 其他代码操作......
}


- (void)applicationDidEnterBackground:(UIApplication *)application {

// 其他代码操作......

  [[NSManagedObjectContext MR_defaultContext] MR_saveOnlySelfAndWait];

// 其他代码操作......

}

 当然我们还得建立Model.xcdatamodel来自定义TestUser类的需求属性,这里省略此操作,添加几个属性而已。

TestUser继承自NSManagedObject

+ (NSString *)MR_entityName {
    // model.xcdatamodelid里对象的名字
      return @"User";
}

从数据库里拿到一个当前用户,这个当前用户应该满足,其属性为登录状态==Yes

+ (TestUser *)currentUser {

  if (!_currentUser) {
    _currentUser =
 [self MR_findFirstByAttribute:NSStringFromSelector(@selector(logged)) 
                             withValue:@YES];
  }

  return _currentUser;
}
    

用户执行了登出操作

- (void)logout {

    // 登出了,当然就没有登录了,状态设置成NO
      [TestUser1 currentUser].logged = NO;

    // 存储变化的对象
  [[NSManagedObjectContext MR_defaultContext] MR_saveOnlySelfAndWait];
    
    // 同时更新偏好里的bool值
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"LOGOUT"]) {
        [[NSUserDefaults standardUserDefaults]setBool:NO forKey:@"LOGOUT"];
        [[NSUserDefaults standardUserDefaults]synchronize];
        return;
   
     }
 
    // 发出用户登出的通知,以后其他控制器,类实例,进行相应的操作
     [[NSNotificationCenter defaultCenter]     postNotificationName:TestUser1DidLogoutNotification object:nil];

}

查找所有某个类的实例

    NSArray *allUsers = [TestUser1 MR_findAll];

        for (TestUser1 *user in allUsers) {
            user.logged = NO;
        }

查找特定条件某个类的实例

    TestUser *user = [TestUser 
    // 查找uid为12345的用户
    MR_findFirstByAttribute:NSStringFromSelector(@selector(uid)) withValue:@(12345)];
                
      if (!user)
      {
    // 没有找到就创建一个TestUser
                user = [TestUser MR_createEntity];
      }

TestUser实例属性变化后,调用

[[NSManagedObjectContext MR_defaultContext] MR_saveOnlySelfAndWait];

其他高级分页,关联的操作,待更新

原文地址:https://www.cnblogs.com/songxing10000/p/5511315.html