开发者

Error : EXC_Bad_Access while accessing a retainCount of an Object

In header file .h

@interface MemoryAppDelegate开发者_开发技巧:NSObject <UIApplicationDelegate> {
Class1 *class1_obj;
}

In Implementation file .m

@implementation Memory : (UIApplication*) application
{
 NSLog(@"Retain Count of class1_obj %d",[class1_obj retainCount]); //ouput retainCount is 0
 Class2 *class2_obj;
 NSLog(@"Retain Count of class2_obj %d",[class2_obj retainCount]); // gives EXC_Bad_Access error

As in the above code, when I declare a object in header file and try to access its retain count is gives me 0. But if I declare the object in implementation file and access its retainCount it throws Bad_Access. Kindly can you say why this error occurs?


First of all : You should not access any object's retaincount in your application.

To answer your question :

  • object1 is an instance variable, it points to nil when not initiated. When you send a message to nil, it returns nil (here, 0).
  • object2 is a pointer that has not been set to anything, not even nil, so it may be pointing to anything. Here, it points to a non-existing object, so it crashes.


Not sure why you do all this, but this code:

 Class2 *class2_obj;
 NSLog(@"Retain Count of class2_obj %d",[class2_obj retainCount]); // gives EXC_Bad_Access error

Only creates a pointer to a certain type of object, it doesn't actually create an instance. So accessing it and asking its retainCount (which you shouldn't do in the first place), will result in a valid crash. Because it is not a valid object (yet). Try initializing it first.

UPDATE: if you insist on doing this, here is something that might work

Class2 *class2_obj = [[Class2 alloc] init];
NSLog(@"Retain Count of class2_obj %d",[class2_obj retainCount]); // gives retain count of 1
[class2_obj release];


Because when you declare it in the class as an instance variable, it's automatically initialized with nil. And [nil retainCount] returns again nil which is 0 when printed as integer (%d)

But a variable which is declared locally is not initialized and such a pointer points just somewhere, most likely to a block of memory which is not allocated. And since trying to access a memory location which is not allocated results in a EXC_BAD_ACCESS you experience the error you described.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜