简体   繁体   中英

Why we need to alloc , init for a mutable object

I don't know if the question was asked previously and Im searching for some good answer.

Question is : Whenever sometimes I don't use [[... alloc] init] for some mutable class , I get crash.

Example :

NSMutableDictionary *myDict = someObject ; //[allocation of some other dictionary object directly without using alloc , init].

For some stages compiler warns me at runtime that you can not change values within myDict even though it is mutable.

Instead of that if I write code :

NSMutableDictionary *myDict = [[NSMutableDictionary alloc] initWithDictionary:someObject]; 

then it works.

So why alloc , init is necessary ? Or What is the problem actually ?

Thanks.

Objective-C is based on C that is not a strongly typed language : you can put object of some type in variable of other type (basically because, in objective-C, they are all represented by their pointers).

When you write:

NSDictionary *immutableDict = [[NSDictionary alloc] init...];
NSMutableDictionary *mutableDict = immutableDict;

you just store the pointer to the immutable dictionary into the variable prepared to store a pointer to a mutable dictionary. But it doesn't magically transform your immutable dictionary in a mutable one.

But when you write:

NSMutableDictionary *mutableDict = [[NSMutableDictionary alloc] initWithDictionary:immutableDict];

you create a mutable dictionary that you initialize (fill) with the values contained in your immutable dictionary. So you can now modifiy your newly allocated mutable dictionary because it is mutable.

This is very basic question there are already number of solutions present to your question ( to understand alloc, init, new refer following )

alloc, init, and new in Objective-C

Use of alloc init instead of new

alloc and init what do they actually do

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