简体   繁体   中英

Objective-C initializing an NSArray vs NSMutableArray

Why does this work:

self.array = newArray;

But this doesn't:

[[self mutableArray] addObject:object];

Meaning, why do I need to init the NSMutableArray for it to work when I don't have to init the NSArray ?

EDIT: Hops this is clearer guys.

Interface:

@interface Foo : UIViewController {

}

@property (nonatomic, retain) NSArray *array;
@property (nonatomic, retain) NSMutableArray *mutableArray;

@end

Implementation:

@implementation Foo

@synthesize array;
@synthesize mutableArray;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.array = [Class returningAnArray];
    [[self mutableArray] addObject:objectIHaveOmittedTheCode];
}

@end
self.array = newArray;

In this line, you are assigning already created object to self.array . So, you've no need to create it.

[[self mutableArray] addObject:object];

But in this line you are trying to add an object to a array which is not created actually. If you don't create the array, it will be nil , and sending message to nil won't take any effect.

In Objective-C NSArray objects are immutable.

self.array = newArray;

This line is a property assignment. The self.array property returns a reference pointing to a location in memory that contains an NSArray object. By assigning the property to different objects you're not really modifying the object themselves.

If you wish to modify an existing NSArray object, you'll have to create a NSMutableArray object containing the same elements:

NSMutableArray *mutableArray = [[NSMutableArray alloc] initWithArray:self.array];
[mutableArray addObject:object];

Note that NSMutableArray inherits from NSArray , so you can safely assign the object referenced by mutableArray to any variable of type NSArray .

[Class returningArray] did the allocation for you. Every object needs to be allocated (and should be initialized) before it can used. The solution is.

- (void)viewDidLoad {
    [super viewDidLoad];
    self.array = [Class returningAnArray];
    self.mutableArray = [NSMutableArray array];
    //Now you can use mutable array
    [[self mutableArray] addObject:objectIHaveOmittedTheCode];
}

Now you have created your array and your mutable array with out explicitly calling alloc on either because those classes have done it for you.

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