Search code examples
iphoneobjective-cioscocoa-touchnslog

In iOS, why objRect can be used but NSLog(@"%@", objRect) will cause bad memory access?


In iOS, objRect is a CGRect object. The code runs fine with

if (objRect.origin.x > 0)  { 
    // do something 
}

but under it, the line

NSLog(@"%@", objRect);

will cause bad memory access (EXC_BAD_ACCESS) and the program will stop. Why is that? Can the object be printed out otherwise?


Solution

  • CGRect is not an Objective-C object, so it cannot respond to [objRect description] (which is what %@ means). It is a structure:

    struct CGRect {
        CGPoint origin;
        CGSize size;
    };
    typedef struct CGRect CGRect;
    

    If you want to log your CGRect, you can use NSStringFromCGRect.