简体   繁体   中英

Assigning autoreleased object to a strong object

Lets say I have a class A with a member variable "myDictionary".

Now if I do this:

myDictionary = [NSDictionary dictionary];

I know that by default members of a class are of strong type. So myDictionary will be available during the lifetime of class A object. Thats what my understanding is about ARC.

But I am getting an EXE_BAC_ACCESS on myDictionary which really confuses me. Do I need to do anything extra in order to avoid EXE_BAD_EXCESS on myDictionary? Because above method returns an autoreleased object.

Thanks in Advance.

If you're not using ARC, then you should use +dictionary any time you need an autoreleased dictionary, and +alloc/init any time you need a dictionary that you're going to hold on to (eg by placing it in an ivar), or alternatively if you simply want to avoid autorelease and -release it manually.

So try to implement like this:

myDictionary = [[NSDictionary alloc] init];

The most likely error here is accessing myDictionary from multiple threads. Ensuring that you always access ivar correctly is one of the several reasons you should always refer to your properties as self.myDictionary rather than directly referring to the _myDictionary ivar. When you need to make this thread-safe, that will ensure there is only one place you need to fix the code.

There are other possible ways to get this error, such as incorrect handling of CFBridging... functions, but the most common is multi-threaded access.

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