简体   繁体   中英

NSMutableArray object thinks it is an NSArray :(

So I have a property NSMutableArray *grades . At the only place where I set this property, I am doing this:

NSMutableArray *array = [[NSMutableArray alloc] init];
self.grades = array;    
[array release];
[self.grades addObject:@"20"];

The last statement generates an exception: -[NSCFArray insertObject:atIndex:]: mutating method sent to immutable object' .

What in the world am I missing?

听起来好像该属性已设置为copy ,这意味着合成的访问器将生成数组的不可变副本

Make sure grades is a NSMutableArray .

Edit:

copy returns an immutable copy, so you can't make changes. From Apple's Objective-C docs :

Copy

If you use the copy declaration attribute, you specify that a value is copied during assignment. If you synthesize the corresponding accessor, the synthesized method uses the copy method. This is useful for attributes such as string objects where there is a possibility that the new value passed in a setter may be mutable (for example, an instance of NSMutableString) and you want to ensure that your object has its own private immutable copy. For example, if you declare a property as follows:

Although this works well for strings, it may present a problem if the attribute is a collection such as an array or a set. Typically you want such collections to be mutable, but the copy method returns an immutable version of the collection . In this situation, you have to provide your own implementation of the setter method, as illustrated in the following example.

Copying the entire collection on assignment is a heavy operation. Are you sure you don't want to retain the collection, or just assign it?

If you really want a mutable copy, then write your own setter as the docs suggest.

- (void)setGrades:(NSMutableArray *)array {
    // make shallow/deep copy here, and assign to `grades`, not `self.grades`
}

What is grades declared as?

From the looks of the error message your declaring grades as an NSArray and while this is valid it does mean that you lose the mutability of the array.

To maintain the array as mutable you'll need to declare grades as an NSMutableArray as well.

edit:

In light of your edit the reason could be that your using the copy keyword in the property, this would mean that when your assigning the array using self.grades the synthesised setter method makes an immutable copy of array

self.grades probably returns an NSArray if declared as @property NSArray* grades seeing this the compiler freaks and does not want to support addObject: method. You have 2 options

  1. cast it like [(NSMutableArray*)self.grades addObject:].
  2. add the object before assigning the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM