crash while removing objects from NSMutableArray

前端 未结 6 539
遇见更好的自我
遇见更好的自我 2021-01-04 00:55

In my iphone project (ARC enabled) i have a nsmuatble array which contains some 5 managed objects (which are retrieved from core data ) and in some scenario i n

相关标签:
6条回答
  • 2021-01-04 01:09

    This:

    [__NSArrayI removeObject:] : unrecognized selector sent to instance 0xa391640
    

    indicates that your array "surveys" is NSArray (not-mutable). Are you sure you have initialized it properly? If you do it by an assignment like this

    NSMutableArray* surveys = [someManagedObjectContext executeFetchRequest:request]
    

    an array "surveys" will be of type NSArray because Core Data fetch requests return NSArrays.

    0 讨论(0)
  • 2021-01-04 01:13

    The error message says it all,

    [__NSArrayI removeObject:]: unrecognized selector
    

    __NSArrayI is a code-word for an immutable array (NSArray), That means your surveys object is not NSMutablArray, but NSArray.

    You cannot add or remove objects from NSArray.

    Check your code. You have assigned NSArray to surveys or you have reinitialized it as NSArray.

    0 讨论(0)
  • 2021-01-04 01:13

    From the exception it's very evident that at some point you are assigning an immutable instance to your mutable array. From the comments I could make out that you were sorting surveys and sorted array was returning immutable array. Type casting will not do good for getting mutableCopy of an immutable object.

    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor1,nil]; 
    surveys = (NSMutableArray *) [[[NSMutableArray alloc]initWithArray:surveys ] sortedArrayUsingDescriptors:sortDescriptors];
    

    Instead of it use

    [surveys sortUsingDescriptors: @[sortDescriptor1]];
    
    0 讨论(0)
  • 2021-01-04 01:18

    The answer is very simple.

    For First case.
    Check the part where you have initialized your array, and check if somewhere through your code, if you have assigned an NSArray to your NSMutableArray object.

    For second case.
    You cannot remove objects from the array while you are enumerating through it. This will result in a crash saying array has mutated while enumerating

    0 讨论(0)
  • 2021-01-04 01:33

    Remove all the things that you are doing and simply do like this

     [surveys removeAllObjects];
    

    As from the error that you are getting so maybe that Array is not NSmutableArray just normal array so thats why you can not remove object from It and you try to do so and app got crash

    check where you have initialised it if it is Mutable or not

    so as I said remove all that thing and use simple removeAllObject

    0 讨论(0)
  • 2021-01-04 01:34

    You might have initialised with Immutable Array. Use the following Code:

    NSMutableArray *newArray = [NSMutableArray arrayWithArray: oldArray];

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