Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c 带NSO操作和ARC的EXC\u坏访问_Objective C_Ios5_Automatic Ref Counting - Fatal编程技术网

Objective c 带NSO操作和ARC的EXC\u坏访问

Objective c 带NSO操作和ARC的EXC\u坏访问,objective-c,ios5,automatic-ref-counting,Objective C,Ios5,Automatic Ref Counting,我有一个应用程序,它在一个旧的项目中运行良好(该项目不使用ARC,是用iOS 4.2在Xcode 4.0中编写的) 我正在尝试将此应用程序移植到Xcode 4.2和iOS 5上,以使用ARC和故事板 我已经把所有的东西都移植过来,并修复了由于保留、释放、解除分配等引起的所有错误。项目现在构建得很好。我还在新项目中重建了我的核心数据模型,并重建了我的模型子类 错误发生的地方是当我尝试在后台线程中解析XML文件时。该文件是项目的本地文件。我为每个进行解析的NSOperation类(共有四个)记录初始

我有一个应用程序,它在一个旧的项目中运行良好(该项目不使用ARC,是用iOS 4.2在Xcode 4.0中编写的)

我正在尝试将此应用程序移植到Xcode 4.2和iOS 5上,以使用ARC和故事板

我已经把所有的东西都移植过来,并修复了由于保留、释放、解除分配等引起的所有错误。项目现在构建得很好。我还在新项目中重建了我的核心数据模型,并重建了我的模型子类

错误发生的地方是当我尝试在后台线程中解析XML文件时。该文件是项目的本地文件。我为每个进行解析的NSOperation类(共有四个)记录初始值设定项。当我到达应用程序的该点时,将操作添加到队列中时会发生错误

以下是我在AppDelegate中启动操作的代码:

#import "AppDelegate.h"
#import "ACHPhonebook.h"

@implementation AppDelegate

@synthesize window = _window;
@synthesize managedObjectContext = __managedObjectContext;
@synthesize managedObjectModel = __managedObjectModel;
@synthesize persistentStoreCoordinator = __persistentStoreCoordinator;

@synthesize parseQueue;
@synthesize parseOpAD, parseOpEK, parseOpLR, parseOpSZ;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"ACHPhonebook" inManagedObjectContext:self.managedObjectContext];

    [request setEntity:entity];    

    NSError *error = nil;
    NSUInteger count = [self.managedObjectContext countForFetchRequest:request error:&error];

    NSLog(@"total CD count = %d", count);

    if(
       getenv("NSZombieEnabled") || getenv("NSAutoreleaseFreedObjectCheckEnabled")
       ) {
        NSLog(@"NSZombieEnabled/NSAutoreleaseFreedObjectCheckEnabled enabled!");
    }

    if (count == 0) {
        // Purge the DB
        [ACHPhonebook purgePhoneBook:self.managedObjectContext];

        // NSLog(@"Just purged the phonebook");

        // Set up the NSOperation Queue for the parsing
        parseQueue = [[NSOperationQueue alloc] init];

        // Make an operation to import the phonebook    
        //[self setParseOp:[[ParseOperation alloc] initAndStartParse]]; 
        [self setParseOpAD:[[ParseOperationA_D alloc] initAndStartParse]];
        [self setParseOpEK:[[ParseOperationE_K alloc] initAndStartParse]];
        [self setParseOpLR:[[ParseOperationL_R alloc] initAndStartParse]];
        [self setParseOpSZ:[[ParseOperationS_Z alloc] initAndStartParse]];

        // [parseQueue addOperation:parseOp];

        NSArray *opArray = [[NSArray alloc] initWithObjects:parseOpAD, parseOpEK, parseOpLR, parseOpSZ, nil];

        [parseQueue addOperations:opArray waitUntilFinished:NO];
    }


//    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
//    // Override point for customization after application launch.
//    self.window.backgroundColor = [UIColor whiteColor];
//    [self.window makeKeyAndVisible];
    return YES;
}
下面是一个NSOperation类(它们都是相同的,只是处理不同的文件,以帮助加快6000条记录的初始加载速度)

#import "ParseOperationA-D.h"
#import "ACHPhonebook.h"
#import "AppDelegate.h"
#import "TBXML.h"

@implementation ParseOperationA_D

- (id)initAndStartParse
{
    NSLog(@"ParseOperation init");

    // [self parsePhonebook];

    return self;

}

- (void)mergeChanges:(NSNotification *)notification
{
    id appDelegate = [[UIApplication sharedApplication] delegate];

    NSManagedObjectContext *mainContext = [appDelegate managedObjectContext];

    // Merge changes into the main context on the main thread
   [mainContext performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:)  
                                withObject:notification
                                waitUntilDone:NO];

    // NSLog(@"Merged Changes");
}

// the main function for this NSOperation, to start the parsing
- (void)main {

    id appDelegate = [[UIApplication sharedApplication] delegate];

    NSManagedObjectContext *ctx = [[NSManagedObjectContext alloc] init];
    [ctx setUndoManager:nil];
    [ctx setPersistentStoreCoordinator: [appDelegate persistentStoreCoordinator]];

    // Register context with the notification center
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; 
    [nc addObserver:self
           selector:@selector(mergeChanges:) 
               name:NSManagedObjectContextDidSaveNotification
             object:ctx];

    NSUInteger x = 1;

    TBXML *tbxml = [[TBXML alloc] initWithXMLFile:@"achcentral_aTOd.xml"];

    // Get root element
    TBXMLElement * root = tbxml.rootXMLElement;

    // if root element is valid
    if (root) {

        NSError *error = nil;

        TBXMLElement *thisPBE = [TBXML childElementNamed:@"PhoneBookResults" parentElement:root];

        while (thisPBE != nil) {

            // Set up the Insert command
            ACHPhonebook * xmlPBE = (ACHPhonebook *)[NSEntityDescription insertNewObjectForEntityForName:@"ACHPhonebook" inManagedObjectContext:ctx];

            // Set all the field values from the XML record

            //            TBXMLElement *elName = [TBXML childElementNamed:@"Name" parentElement:thisPBE];
            //            if (elName != nil) {
            //                [xmlPBE setName:[TBXML textForElement:elName]];
            //            }

            TBXMLElement *elTitle = [TBXML childElementNamed:@"title" parentElement:thisPBE];
            if (elTitle != nil) {
                [xmlPBE setTitle:[TBXML textForElement:elTitle]];
            }

            TBXMLElement *elDept = [TBXML childElementNamed:@"department" parentElement:thisPBE];
            if (elDept != nil) {
                // obtain the text from the description element
                [xmlPBE setDepartment:[TBXML textForElement:elDept]];
            }

            TBXMLElement *elExt = [TBXML childElementNamed:@"phone" parentElement:thisPBE];
            if (elExt != nil) {
                [xmlPBE setExt:[TBXML textForElement:elExt]];
            }

            TBXMLElement *elPager = [TBXML childElementNamed:@"pager" parentElement:thisPBE];
            if (elPager != nil) {
                [xmlPBE setPager:[TBXML textForElement:elPager]];
            }

            TBXMLElement *elEmailAddress = [TBXML childElementNamed:@"emailaddress" parentElement:thisPBE];
            if (elEmailAddress != nil) {
                [xmlPBE setEmailAddress:[TBXML textForElement:elEmailAddress]];
            }

            //            TBXMLElement *elNetworkID = [TBXML childElementNamed:@"NetworkID" parentElement:thisPBE];
            //            if (elNetworkID != nil) {
            //                [xmlPBE setNetworkid:[TBXML textForElement:elNetworkID]];
            //            }

            TBXMLElement *elLastName = [TBXML childElementNamed:@"lastName" parentElement:thisPBE];
            if (elLastName != nil) {
                [xmlPBE setLastName:[TBXML textForElement:elLastName]];
            }

            TBXMLElement *elFirstName = [TBXML childElementNamed:@"firstName" parentElement:thisPBE];
            if (elFirstName != nil) {
                [xmlPBE setFirstName:[TBXML textForElement:elFirstName]];
            }

            if (elFirstName != nil && elLastName !=nil) {
                // Make the name field from the first and last names
                NSString *fullName = [[TBXML textForElement:elFirstName] stringByAppendingFormat:@" %@",[TBXML textForElement:elLastName]];
                [xmlPBE setName:fullName];
            }

            TBXMLElement *elPicLoc = [TBXML childElementNamed:@"picFileName" parentElement:thisPBE];
            if (elPicLoc != nil) {
                if (![[TBXML textForElement:elPicLoc] isEqualToString:@""])
                {
                    [xmlPBE setPicloc:[TBXML textForElement:elPicLoc]];

                    NSString *picFilePath = @"https://secure.archildrens.org/insite/badgepics/adbadgepics/";

                    NSURL *url = [NSURL URLWithString:[picFilePath 
                                        stringByAppendingString:xmlPBE.picloc]];
                    NSData * imageData = [[NSData alloc] initWithContentsOfURL: url];
                    if (!imageData)
                    {
                        // The image filename was stored but didn't exist
                        NSString *achImage = 
                        [[NSBundle mainBundle] pathForResource:@"ach" ofType:@"png"]; 
                        imageData = [NSData dataWithContentsOfFile:achImage];
                    }

                    [xmlPBE setPicture:imageData];

                }
            }

            if (x % 50 == 0) {
                // Get ready to save the context
                error = nil;
                // Save the context.
                if (![ctx save:&error])
                {
                    NSLog(@"loadPhoneBook error %@, %@", error, [error userInfo]);
                    abort();
                }

                // Clear out the scratchpad
                [ctx reset];

                //NSLog(@"Got 10");
            }
            // Find the next XML record (this will end the while loop when we reach the end)
            thisPBE = [TBXML nextSiblingNamed:@"PhoneBookResults" searchFromElement:thisPBE];

            // Increment the counter
            x++;

        } // while ...

        if ([ctx hasChanges]) {

            // NSUInteger *left = [[ctx insertedObjects] count];
            error = nil;
            // Save the context.
            if (![ctx save:&error])
            {
                NSLog(@"loadPhoneBook error %@, %@", error, [error userInfo]);
                abort();
            }

            // Clear out the scratchpad
            [ctx reset];

            NSLog(@"Got the last ones, %d", x);
        }

    }
}

@end
我已尝试启用
NSZombies
,但仍然看不到发生了什么。它总是会因服务器上出现
EXC\u BAD\u访问错误而中断

[parseQueue addOperations:opArray waitUntilFinished:NO]; 

AppDelegate
中的第行,这是我第一次尝试在iOS应用程序中使用多线程。正如我之前所说,我有一个版本是根据旧版本的SDK构建的,它仍然在运行。这可能是(也可能是)我忽略了一件非常简单的事情…

而不是使用NSOperations,您尝试了自执行self-performSelectorInBackground:withObject:?

设置,并且(您可能已经完成了这一步)在调试器中。然后,当您的应用程序崩溃时,在gdb控制台中键入以下内容:

(gdb) info malloc-history 0x543216
0x543216
替换为导致崩溃的对象的地址,您将获得一个更有用的堆栈跟踪,它将帮助您确定代码中导致问题的确切行


我没有。我认为使用NSOperations是创建后台线程的首选方法,可以做很多工作。你能解释一下为什么这种方法比使用NSOperations和NSOperationQueue更好吗?请看,这并不是我不应该使用NSOperations的原因(这就是我在苹果开发网站上看到的示例应用程序所使用的)从性能上讲,线程与NS操作和PrimeStudioBeLoad背景之间的差别是最小的。我将尝试PrimeStudioBeLoad,如果它不崩溃,我会把它称为更好。这仍然不能让我知道问题是什么。我真的想解决这个问题,而不仅仅是创可贴。谢谢。ode>initAndStartParse
方法未调用
self=[super init];
。我认为您没有正确实例化NSOperation子类。这正是问题所在。一旦我修复了项目编译没有错误并且运行良好的问题。请参阅我对上面sho评论的评论。虽然使用Zombies和malloc并没有解决这一问题,但从那时起,这个答案帮助我找到了另外两个问题:)