NSMutableArray removeObjectAtIndex: throws invalid argument exception

前端 未结 3 801
不知归路
不知归路 2021-01-18 05:41

I\'m writing an application to show some news from a portal. The news are fetched using a JSON file from the Internet and then stored into a NSMutableArray using the CoreDat

相关标签:
3条回答
  • 2021-01-18 06:15

    Verify that dataSet is an NSMutableArray. The exception is getting thrown because it doesn't respond to removeObjectAtIndex.

    0 讨论(0)
  • 2021-01-18 06:21

    jdot is correct dataSet must be NSMutableArray..

    you must do it this way..

      dataSet = [NSMutableArray arrayWithArray:[[NewsFetcher sharedInstance] 
                                   fetchManagedObjectsForEntity:@"News" 
                                   withPredicate:predicate
                                   withDescriptor:@"Titolo"]]; 
    

    Now the dataSet is a mutable instance of the array you got from NewsFetcher and it won't crash on removing objects.

    0 讨论(0)
  • 2021-01-18 06:22

    Your NewsFetcher returns you an immutable array, not a mutable instance. Use the following instead for initialization:

    NSArray *results = [[NewsFetcher sharedInstance] 
                         fetchManagedObjectsForEntity:@"News" 
                         withPredicate:predicate
                         withDescriptor:@"Titolo"];
    dataSet = [results mutableCopy];
    

    An expression like A *a = (A*)b; only casts the pointer to a different type - it doesn't convert/change the actual type of the instance it points to.

    0 讨论(0)
提交回复
热议问题