2012-03-01 62 views
1

我想不通爲什麼這個代碼返回一個錯誤NSFetchRequest返回值

- (void) deleteCategoriesWithNoProducts{ 
    NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Category" inManagedObjectContext:self.itemDatabase.managedObjectContext]; 
    [request setEntity:entity]; 

    //NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Category"]; 


    NSSortDescriptor *sortDescriptor = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)]];  

    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; 
    [request setSortDescriptors:sortDescriptors]; 

    NSError *error; 
    NSArray *fetchResults = [self.itemDatabase.managedObjectContext executeFetchRequest:request error:&error]; 


} 

這裏的錯誤:

-[__NSArrayI key]: unrecognized selector sent to instance 0x8267ad0 
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI key]: unrecognized selector sent to instance 0x8267ad0' 

希望有人能幫助我。謝謝!

回答

3

這是你的錯誤:

NSSortDescriptor *sortDescriptor = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)]];  

應該是:

NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)];  

那行本來應該給你的編譯器警告,太。

+0

也不要忘記在你的方法結束時釋放資源。 – ggfela 2012-03-01 12:17:13

+0

除非他使用ARC – yuji 2012-03-01 12:18:11

+0

哦,我看,有點棘手啊。感謝@yuji指出這一點。 – acecapades 2012-03-02 01:36:42