长篇小说,我厌倦了与NSManagedobjectContext相关联的荒谬的并发规则(或者说,如果您尝试跨线程共享一个NSManagedobjectContext,那么它完全不支持并发性和易于爆发的趋势,或者做其他不正确的事情)实现线程安全的变体.

基本上我所做的是创建一个跟踪它创建的线程的子类,然后将所有的方法调用映射到该线程.这样做的机制有点复杂,但关键是我有一些帮助方法,如:

- (NSInvocation*) invocationWithSelector:(SEL)selector {
    //creates an NSInvocation for the given selector
    NSMethodSignature* sig = [self methodSignatureForSelector:selector];    
    NSInvocation* call = [NSInvocation invocationWithMethodSignature:sig];
    [call retainArguments];
    call.target = self;

    call.selector = selector;

    return call;
}

- (void) runInvocationOnContextThread:(NSInvocation*)invocation {
    //performs an NSInvocation on the thread associated with this context
    NSThread* currentThread = [NSThread currentThread];
    if (currentThread != myThread) {
        //call over to the correct thread
        [self performSelector:@selector(runInvocationOnContextThread:) onThread:myThread withObject:invocation waitUntilDone:YES];
    }
    else {
        //we're okay to invoke the target Now
        [invocation invoke];
    }
}


- (id) runInvocationReturningObject:(NSInvocation*) call {
    //returns object types only
    [self runInvocationOnContextThread:call];

    //Now grab the return value
    __unsafe_unretained id result = nil;
    [call getReturnValue:&result];
    return result;
}

…然后子类实现NSManagedContext接口,遵循以下模式:

- (NSArray*) executeFetchRequest:(NSFetchRequest *)request error:(NSError *__autoreleasing *)error {
    //if we're on the context thread,we can directly call the superclass
    if ([NSThread currentThread] == myThread) {
        return [super executeFetchRequest:request error:error];
    }

    //if we get here,we need to remap the invocation back to the context thread
    @synchronized(self) {
        //execute the call on the correct thread for this context
        NSInvocation* call = [self invocationWithSelector:@selector(executeFetchRequest:error:) andArg:request];
        [call setArgument:&error atIndex:3];
        return [self runInvocationReturningObject:call];
    }
}

…然后我用一些代码测试它:

- (void) testContext:(NSManagedobjectContext*) context {
    while (true) {
        if (arc4random() % 2 == 0) {
            //insert
            MyEntity* obj = [NSEntityDescription insertNewObjectForEntityForName:@"MyEntity" inManagedobjectContext:context];
            obj.someNumber = [NSNumber numberWithDouble:1.0];
            obj.anotherNumber = [NSNumber numberWithDouble:1.0];
            obj.aString = [Nsstring stringWithFormat:@"%d",arc4random()];

            [context refreshObject:obj mergeChanges:YES];
            [context save:nil];
        }
        else {
            //delete
            NSArray* others = [context fetchObjectsForEntityName:@"MyEntity"];
            if ([others lastObject]) {
                MyEntity* target = [others lastObject];
                [context deleteObject:target];
                [context save:nil];
            }
        }
        [NSThread sleepForTimeInterval:0.1];
    }
}

所以本质上,我提出了一些针对上述入口点的线程,并且它们随机创建和删除实体.这几乎是应该的方式.

问题是,在调用obj时,经常有一个线程将获得一个EXC_BAD_ACCESS.< field> =< value&gt ;;.对我来说不清楚是什么问题,因为如果我在调试器中打印obj,一切都看起来不错.关于什么问题可能是什么的建议(除了苹果推荐对NSManagedobjectContext进行子类化的事实)以及如何解决? 附:我知道GCD和NSOperationQueue以及其他通常用来“解决”这个问题的技术.没有一个提供我想要的.我正在寻找的是一个NSManagedobjectContext,可以自由,安全和直接地使用任何数量的线程来查看和更改应用程序状态,而不需要任何外部同步.

解决方法

正如noa正确指出的那样,问题是尽管我已经使NSManagedobjectContext线程安全,但我没有将NSManagedobject实例本身检测为线程安全.线程安全上下文和非线程安全实体之间的交互对我的定期崩溃负责.

如果有人感兴趣,我创建了一个线程安全的NSManagedobject子类,通过注入我自己的setter方法来代替Core Data通常会生成的一些方法.这是使用以下代码实现的:

//implement these so that we kNow what thread our associated context is on
- (void) awakeFromInsert {
    myThread = [NSThread currentThread];
}
- (void) awakeFromFetch {
    myThread = [NSThread currentThread];
}

//helper for re-invoking the dynamic setter method,because the NSInvocation requires a @selector and dynamicSetter() isn't one
- (void) recallDynamicSetter:(SEL)sel withObject:(id)obj {
    dynamicSetter(self,sel,obj);
}

//mapping invocations back to the context thread
- (void) runInvocationOnCorrectThread:(NSInvocation*)call {
    if (! [self myThread] || [NSThread currentThread] == [self myThread]) {
        //okay to invoke
        [call invoke];
    }
    else {
        //remap to the correct thread
        [self performSelector:@selector(runInvocationOnCorrectThread:) onThread:myThread withObject:call waitUntilDone:YES];
    }
}

//magic!  perform the same operations that the Core Data generated setter would,but only after ensuring we are on the correct thread
void dynamicSetter(id self,SEL _cmd,id obj) {
    if (! [self myThread] || [NSThread currentThread] == [self myThread]) {
        //okay to execute
        //XXX:  clunky way to get the property name,but meh...
        Nsstring* targetSel = NsstringFromSelector(_cmd);
        Nsstring* propertyNameUpper = [targetSel substringFromIndex:3];  //remove the 'set'
        Nsstring* firstLetter = [[propertyNameUpper substringToIndex:1] lowercaseString];
        Nsstring* propertyName = [Nsstring stringWithFormat:@"%@%@",firstLetter,[propertyNameUpper substringFromIndex:1]];
        propertyName = [propertyName substringToIndex:[propertyName length] - 1];

        //NSLog(@"Setting property:  name=%@",propertyName);

        [self willChangeValueForKey:propertyName];
        [self setPrimitiveValue:obj forKey:propertyName];
        [self didChangeValueForKey:propertyName];

    }
    else {
        //call back on the correct thread
        NSMethodSignature* sig = [self methodSignatureForSelector:@selector(recallDynamicSetter:withObject:)];
        NSInvocation* call = [NSInvocation invocationWithMethodSignature:sig];
        [call retainArguments];
        call.target = self;
        call.selector = @selector(recallDynamicSetter:withObject:);
        [call setArgument:&_cmd atIndex:2];
        [call setArgument:&obj atIndex:3];

        [self runInvocationOnCorrectThread:call];
    }
}

//bootstrapping the magic; watch for setters and override each one we see
+ (BOOL) resolveInstanceMethod:(SEL)sel {
    Nsstring* targetSel = NsstringFromSelector(sel);
    if ([targetSel startsWith:@"set"] && ! [targetSel contains:@"Primitive"]) {
        NSLog(@"Overriding selector:  %@",targetSel);
        class_addMethod([self class],(IMP)dynamicSetter,"v@:@");
        return YES;
    }

    return [super resolveInstanceMethod:sel];
}

这与我的线程安全上下文实现一起解决了问题,让我想到了;一个线程安全的环境,我可以传递给任何我想要的人,而不必担心后果.

当然这不是一个防弹解决方案,因为我已经确定了至少以下限制:

/* Also note that using this tool carries several small caveats:
 *
 *      1.  All entities in the data model MUST inherit from 'ThreadSafeManagedobject'.  Inheriting directly from 
 *          NSManagedobject is not acceptable and WILL crash the app.  Either every entity is thread-safe,or none 
 *          of them are.
 *
 *      2.  You MUST use 'ThreadSafeContext' instead of 'NSManagedobjectContext'.  If you don't do this then there 
 *          is no point in using 'ThreadSafeManagedobject' (and vice-versa).  You need to use the two classes together,*          or not at all.  Note that to "use" ThreadSafeContext,all you have to do is replace every [[NSManagedobjectContext alloc] init]
 *          with an [[ThreadSafeContext alloc] init].
 *
 *      3.  You SHOULD NOT give any 'ThreadSafeManagedobject' a custom setter implementation.  If you implement a custom 
 *          setter,then ThreadSafeManagedobject will not be able to synchronize it,and the data model will no longer 
 *          be thread-safe.  Note that it is technically possible to work around this,by replicating the synchronization
 *          logic on a one-off basis for each custom setter added.
 *
 *      4.  You SHOULD NOT add any additional @dynamic properties to your object,or any additional custom methods named
 *          like 'set...'.  If you do the 'ThreadSafeManagedobject' superclass may attempt to override and synchronize 
 *          your implementation.
 *
 *      5.  If you implement 'awakeFromInsert' or 'awakeFromFetch' in your data model class(es),thne you MUST call 
 *          the superclass implementation of these methods before you do anything else.
 *
 *      6.  You SHOULD NOT directly invoke 'setPrimitiveValue:forKey:' or any variant thereof.  
 *
 */

然而,对于大多数典型的中小型项目,我认为线程安全数据层的好处明显超过了这些限制.

ios – 使核心数据线程安全的更多相关文章

  1. Html5跳转到APP指定页面的实现

    这篇文章主要介绍了Html5跳转到APP指定页面的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

  2. ios – 比较两个版本号

    如何比较两个版本号字符串?例如:3.1.1和3.1.2.5.4现在我需要找出3.1.2.5.4是否高于3.1.1但我不知道如何做到这一点.有谁能够帮我?

  3. iOS:无法获取Caches目录的内容

    试图获取Caches目录的内容:路径是正确的,我可以在Finder中看到它存在并包含我的文件.directoryItems是nil,错误是我怎么了?解决方法你使用错误的路径.要为应用程序获取正确的缓存目录,请使用此:在cacheDirectory中,您将收到这样的字符串路径:整个代码:

  4. ios – 如何使用CNContactVCardSerialization dataWithContacts:方法获取联系人图像的VCF数据?

    我正在使用CNContacts和CNContactUI框架并通过此选择联系人和此联系对象具有contact.imageData和日志.但当我试图通过交叉检查这些数据这是空的:为什么我收到此null并且此联系人在签入联系人时有图像?

  5. iOS:核心图像和多线程应用程序

    我试图以最有效的方式运行一些核心图像过滤器.试图避免内存警告和崩溃,这是我在渲染大图像时得到的.我正在看Apple的核心图像编程指南.关于多线程,它说:“每个线程必须创建自己的CIFilter对象.否则,你的应用程序可能会出现意外行为.”这是什么意思?我实际上是试图在后台线程上运行我的过滤器,所以我可以在主线程上运行HUD(见下文).这在coreImage的上下文中是否有意义?

  6. ios – 签名无效:oauth_signature

    我正在尝试生成oauth_signature以使用FatsecretAPI,但是获得无效的签名错误–无法弄清楚原因.我尝试尽可能准确地遵循here所述的所有步骤(参见步骤2)来生成签名值.他们说:UsetheHMAC-SHA1signaturealgorithmasdefinedbythe[RFC2104]tosigntherequestwheretextistheSignatureBaseStr

  7. ios – 在没有alloc init的情况下将NSString转换为NSAttributedString

    解决方法我建议在Nsstring上创建一个类别,使用一种方法将其转换为NSAttributedString,然后在整个项目中使用该辅助方法.像这样:

  8. ios – 确定图像选择器媒体类型是否为视频

    优选地,包括“所有图像类型”或“所有视频类型”的方式.解决方法最好检查一下与特定UTI的一致性.现在,iOS告诉你它是一个public.movie,但它明年会说些什么呢?你会看到有人检查public.video.太棒了,所以你硬编码了两种而不是一种.但问“这是一部电影吗?”而不是硬编码您认为iOS将返回的特定类型?

  9. ios – 使用NSURLSession获取JSON数据

    我试图从谷歌距离api使用NSURLSession获取数据,但如下所示,当我打印响应和数据时,我得到的结果为NULL.可能是什么问题?

  10. xcode – 如何在调试中查看NSString中的文本

    我是XCode4的新手,我无法弄清楚如何在断点中查看变量(如NSCFString)的值.我看到我的Autos/Local但它们显示Hex值并且SummaryUnavailable.我想要做的就是将字符串本身视为常规文本.我甚至徘徊在变量上,期望在VisualStudio中看到他们的价值而没有运气.解决方法打开调试器的控制台视图,并在提示符下键入:要么

随机推荐

  1. iOS实现拖拽View跟随手指浮动效果

    这篇文章主要为大家详细介绍了iOS实现拖拽View跟随手指浮动,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  2. iOS – genstrings:无法连接到输出目录en.lproj

    使用我桌面上的项目文件夹,我启动终端输入:cd然后将我的项目文件夹拖到终端,它给了我路径.然后我将这行代码粘贴到终端中找.-name*.m|xargsgenstrings-oen.lproj我在终端中收到此错误消息:genstrings:无法连接到输出目录en.lproj它多次打印这行,然后说我的项目是一个目录的路径?没有.strings文件.对我做错了什么的想法?

  3. iOS 7 UIButtonBarItem图像没有色调

    如何确保按钮图标采用全局色调?解决方法只是想将其转换为根注释,以便为“回答”复选标记提供更好的上下文,并提供更好的格式.我能想出这个!

  4. ios – 在自定义相机层的AVFoundation中自动对焦和自动曝光

    为AVFoundation定制图层相机创建精确的自动对焦和曝光的最佳方法是什么?

  5. ios – Xcode找不到Alamofire,错误:没有这样的模块’Alamofire’

    我正在尝试按照github(https://github.com/Alamofire/Alamofire#cocoapods)指令将Alamofire包含在我的Swift项目中.我创建了一个新项目,导航到项目目录并运行此命令sudogeminstallcocoapods.然后我面临以下错误:搜索后我设法通过运行此命令安装cocoapodssudogeminstall-n/usr/local/bin

  6. ios – 在没有iPhone6s或更新的情况下测试ARKit

    我在决定下载Xcode9之前.我想玩新的框架–ARKit.我知道要用ARKit运行app我需要一个带有A9芯片或更新版本的设备.不幸的是我有一个较旧的.我的问题是已经下载了新Xcode的人.在我的情况下有可能运行ARKit应用程序吗?那个或其他任何模拟器?任何想法或我将不得不购买新设备?解决方法任何iOS11设备都可以使用ARKit,但是具有高质量AR体验的全球跟踪功能需要使用A9或更高版本处理器的设备.使用iOS11测试版更新您的设备是必要的.

  7. 将iOS应用移植到Android

    我们制作了一个具有2000个目标c类的退出大型iOS应用程序.我想知道有一个最佳实践指南将其移植到Android?此外,由于我们的应用程序大量使用UINavigation和UIView控制器,我想知道在Android上有类似的模型和实现.谢谢到目前为止,guenter解决方法老实说,我认为你正在计划的只是制作难以维护的糟糕代码.我意识到这听起来像很多工作,但从长远来看它会更容易,我只是将应用程序的概念“移植”到android并从头开始编写.

  8. ios – 在Swift中覆盖Objective C类方法

    我是Swift的初学者,我正在尝试在Swift项目中使用JSONModel.我想从JSONModel覆盖方法keyMapper,但我没有找到如何覆盖模型类中的Objective-C类方法.该方法的签名是:我怎样才能做到这一点?解决方法您可以像覆盖实例方法一样执行此操作,但使用class关键字除外:

  9. ios – 在WKWebView中获取链接URL

    我想在WKWebView中获取tapped链接的url.链接采用自定义格式,可触发应用中的某些操作.例如HTTP://我的网站/帮助#深层链接对讲.我这样使用KVO:这在第一次点击链接时效果很好.但是,如果我连续两次点击相同的链接,它将不报告链接点击.是否有解决方法来解决这个问题,以便我可以检测每个点击并获取链接?任何关于这个的指针都会很棒!解决方法像这样更改addobserver在observeValue函数中,您可以获得两个值

  10. ios – 在Swift的UIView中找到UILabel

    我正在尝试在我的UIViewControllers的超级视图中找到我的UILabels.这是我的代码:这是在Objective-C中推荐的方式,但是在Swift中我只得到UIViews和CALayer.我肯定在提供给这个方法的视图中有UILabel.我错过了什么?我的UIViewController中的调用:解决方法使用函数式编程概念可以更轻松地实现这一目标.

返回
顶部