What causes this EXC_CRASH in my iPad app? - objective-c

I got this symbolicated stack trace from a crash report from my iPad app (excerpt):
Exception Type: EXC_CRASH (SIGABRT)
Exception Codes: 0x00000000, 0x00000000
Crashed Thread: 0
0 ImageIO 0x34528eb4 _CGImagePluginIdentifyPNG + 0
1 ImageIO 0x34528d90 _CGImageSourceBindToPlugin + 368
2 ImageIO 0x34528bda CGImageSourceGetCount + 26
3 UIKit 0x341b8f66 _UIImageRefAtPath + 366
4 UIKit 0x342650ce -[UIImage initWithContentsOfFile:] + 50
5 UIKit 0x342b0314 +[UIImage imageWithContentsOfFile:] + 28
6 DesignScene 0x00013a2a -[LTImageCache fetchImageforURL:] (LTImageCache.m:37)
…
Here are the contents of -[LTImageCache fetchImageforURL:]:
- (UIImage *)fetchImageforURL:(NSString *)theUrl {
NSString *key = theUrl.md5Hash;
return [UIImage imageWithContentsOfFile:[self filenameForKey:key]];
}
And the contents of -[LTImageCache filenameForKey:]:
- (NSString *) filenameForKey:(NSString *) key {
return [_cacheDir stringByAppendingPathComponent:key];
}
The _cacheDir ivar is created and retained in -init. So the question is, what caused this crash? Is the problem that:
the return value of -[LTImageCache filenameForKey:] needs to be retained (it's autoreleased)
An unhandled exception somewhere (+[UIImage imageWithContentsOfFile:] claims to return nil if the image is unrecognizable)
Something else…I'm out of guesses
I would think that an autoreleased value would be fine. An in truth, this code has been working fine for months, and this method is called 100s of times in a session. This is a rare crash under very specific circumstances (the app left loaded overnight, crash upon unlocking the iPad in the morning).
What's causing this crash?

I'm guessing but it looks like a bogus image file. Is this in your app bundle or do you download it?
I don't think it has anything to do with memory mgt.
To test you could try using ImageIO to open the file yourself.
CGImageSourceRef imageSource = CGImageSourceCreateWithURL((CFURLRef)self.url, NULL);
if(NULL != imageSource) {
size_t imageCount = CGImageSourceGetCount(imageSource);
if(imageCount > 0) {
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], kCGImageSourceCreateThumbnailFromImageIfAbsent,
[NSNumber numberWithInteger:maxSize], kCGImageSourceThumbnailMaxPixelSize, nil];
CGImageRef thumbImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, (CFDictionaryRef)options);
self.image = [UIImage imageWithCGImage:thumbImage scale:scale orientation:imageOrientation];
CGImageRelease(thumbImage);
CFRelease(imageSource);
[pool drain];
}
} else {
NSLog(#"Unable to open image %#", self.url);
}
and then try to find the image count.
Using maxSize and getting a thumbnail will ensure you don't load a 5 mega-pixel image to put into a 100x100 tile on your UI.
scale is the window's scale (will be 2 for iPhone 4 and 1 for everything else).
To find the orientation you need to use the CGImageSourceCopyPropertiesAtIndex function and then the kCGImagePropertyOrientation key to get the orientation of the particular image.

Related

autosavesInPlace causes New Document save to fail

I have a NSPersistentDocument based app which fails to save a new document when autosavesInPlace is set to return YES , return NO and the problem disappears.
I create a new document
Make some changes
Save it , thus running NSSaveAsOperation , the name of the document and the URL changes and all appears to be well but the next save will throw a very descriptive
NSPersistentStoreSaveError = 134030, // unclassified save error - something we depend on returned an error
This only happens when the document attempts to run a save after a NSSaveAsOperation. Any other save type will work fine as in changes to existing doc. Interesting effect is that if i dont change name or location i dont get this issue either.
Im getting an exception backtrace of
frame #0: 0x00007fff988143c5 libobjc.A.dylibobjc_exception_throw
frame #1: 0x00007fff94c5f5f9 CoreData-[NSPersistentStore(_NSInternalMethods) _preflightCrossCheck] + 697
frame #2: 0x00007fff94c3198b CoreData-[NSPersistentStoreCoordinator executeRequest:withContext:error:] + 603
frame #3: 0x00007fff94c5aa98 CoreData-[NSManagedObjectContext save:] + 456
frame #4: 0x00007fff91baa101 AppKit-[NSPersistentDocument writeToURL:ofType:forSaveOperation:originalContentsURL:error:] + 3743
frame #5: 0x0000000100002de7 ZZZZ-[ZZZZDocument writeToURL:ofType:forSaveOperation:originalContentsURL:error:] + 135 at ZZZZDocument.m:209
frame #6: 0x00007fff91baabc7 AppKit-[NSPersistentDocument writeSafelyToURL:ofType:forSaveOperation:error:] + 611
frame #7: 0x0000000100002ea3 ZZZZ-[ZZZZDocument writeSafelyToURL:ofType:forSaveOperation:error:] + 115 at ZZZZDocument.m:223
any ideas?
Its not possible for a un-wrappered core data file
In the event you attempt to trap NSSaveAsOperation and do a migrate on the persistent store for that enum the construction of the ...-journal file will fail to create as its outside the sandbox.
-(void)saveToURL:(NSURL *)url ofType:(NSString *)typeName forSaveOperation:(NSSaveOperationType)saveOperation completionHandler:(void (^)(NSError *))completionHandler
{
NSLog(#" save op = %ld to %# ",saveOperation,url);
NSURL *targeturl = url;
if(saveOperation == NSSaveAsOperation)
{
//migrate pstore
NSPersistentStore *store = [self.managedObjectContext.persistentStoreCoordinator.persistentStores lastObject];
if (store)
{
NSMutableDictionary *opts = [NSMutableDictionary dictionary];
[opts setValue:[NSNumber numberWithBool:YES] forKey:NSInferMappingModelAutomaticallyOption];
[opts setValue:[NSNumber numberWithBool:YES] forKey:NSMigratePersistentStoresAutomaticallyOption];
NSError *error = NULL;
NSPersistentStore *newstore = [self.managedObjectContext.persistentStoreCoordinator migratePersistentStore:store toURL:url options:opts withType:store.type error:&error];
if(newstore == nil)
{
NSLog(#"migration error %#",[error localizedDescription]);
}
self.fileURL = url;
}
}
[super saveToURL:targeturl ofType:typeName forSaveOperation:saveOperation completionHandler:completionHandler];
}
So we need to wrapper the file in a bundle/folder which is non-trivial using the NSPersistentDocument framework.
Heres waiting for NSManagedDocument (thats a wishing well API)

Autorelease methods leaking

Hi everyone,
I'm stuck these days on some memory leaks. The app I'm making is working like that :
1 - Loads a file into memory
2 - Create a screen according to some values read on that file
3 - Display the view
Far from now everything is normal when I start the app and get the first screen. There is no leaks.
But when I want to load an other screen from the current view I got plenty of leaks from autoreleased objects. And I don't understand because when I load a new view from the current one the process is similar :
1 - Desctruction of the current view
2 - Loads a file into memory
3 - Create a screen according to some values read on that file
4 - Display the view
Here are some concrete example of what is leaking :
-(NSString*)pathForApplicationName:(NSString*)appName
withImage:(NSString*)imagePath {
NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [searchPaths lastObject];
return [NSString stringWithFormat:#"%#/%#/assets/www/%#",documentPath,[self convertSpacesInDashes:appName],imagePath];
}
The stringWithFormat:.. is leaking. An other example :
-(UIColor*)convertHexColorToUIColor:(NSString*)hexColor {
if ([hexColor length] == 7) {
unsigned c = 0;
NSScanner *scanner = [NSScanner scannerWithString:hexColor];
[scanner setScanLocation:1];
[scanner scanHexInt:&c];
return [UIColor colorWithRed:((c>>16)&0xFF)/255.0
green:((c>>8)&0xFF)/255.0
blue:(©&0xFF)/255.0
alpha:1.];
}
else {
return nil;
}
}
Same, colorWithRed:.. is leaking.
I've read apple's documentation regarding autoreleased objects. And I've even tried to recreate a new pool like that, without any success :
-(UIView)myFonctionWhoGenerateScreens:
for () {
NSAutoreleasePool *subPool = [[NSAutoreleasePool alloc] init];
// There are all of the autoreleased method calls that are leaking...
[subPool drain];
}
}
I think I am missing something. Does anyone has an idea?
Leak backtrace
Thanks a lot.
Edit :
Here is how the return of the leaking function is handled in applyPropertyName:withPropertyType:onComponent:withValue:forStyling method :
else if ([propertyType isEqualToString:#"AB_IMAGE"]) {
UIImage *image = [UIImage imageWithContentsOfFile:[self pathForApplicationName:applicationName
withImage:value]];
#try {
[component setValue:image
forKey:propertyName];
}
#catch (NSException *exception) {
#if DEBUG_CONTROLLER
NSLog(#" %# Not key-value compliant for <%#,%#>",component,propertyName,image);
#endif
}
}
Edit 2 :
Here is the complete back trace http://ganzolo.free.fr/leak/%20Leak.zip
Looking at your Leak document, and picking the [NSString stringWithFormat] object at address 0xdec95c0 as an example, it shows balanced retain count operations for the Foundation, ImageIO, and CoreGraphics use of the object but ABTwoImageItemImageLeftComponent is still holding an unreleased reference.
0 0xdec95c0 CFString (immutable) Malloc 1 00:39.994.343 144 Foundation +[NSString stringWithFormat:]
1 0xdec95c0 CFString (immutable) Autorelease <null> 00:39.994.376 0 Foundation +[NSString stringWithFormat:]
2 0xdec95c0 CFString (immutable) CFRetain 2 00:39.994.397 0 iOS Preview App -[ABTwoImageItemImageLeftComponent setSrcProperty:]
3 0xdec95c0 CFString (immutable) CFRetain 3 00:39.996.231 0 ImageIO CGImageReadCreateWithFile
4 0xdec95c0 CFString (immutable) CFRetain 4 00:39.998.012 0 CoreGraphics CGPropertiesSetProperty
5 0xdec95c0 CFString (immutable) CFRelease 3 00:40.362.865 0 Foundation -[NSAutoreleasePool release]
6 0xdec95c0 CFString (immutable) CFRelease 2 01:14.892.330 0 CoreGraphics CGPropertiesRelease
7 0xdec95c0 CFString (immutable) CFRelease 1 01:14.892.921 0 ImageIO releaseInfoJPEG

Large Image Processing (ARC) Major memory leaks

My iPad app that I am creating has to be able to create the tiles for a 4096x2992 image that is generated earlier in my app..
4096x2992 image isn't very complex (what i'm testing with) and when written to file in png format is approximately 600kb...
On the simulator, this code seems to work fine however when I run the app in tighter memory conditions (on my iPad) the process quits because it ran out of memory...
I've been using the same code in the app previously what was working fine (was only creating tiles for 3072x2244 images however)...
Either I must be doing something stupidly wrong or my #autoreleasepool's aren't working as they should (i think i mentioned that im using ARC)... When running in instruments I can just see the memory used climb up until ~500mb where it then crashes!
I've analysed the code and it hasn't found a single memory leak related to this part of my app so I'm really confused on why this is crashing on me...
Just a little history on how my function gets called so you know whats happening... The app uses CoreGraphics to render a UIView (4096x2992) with some UIImageView's inside it then it sends that UIImage reference into my function buildFromImage: (below) where it begins cutting up/resizing the image to create my file...
Here is the buildFromImage: code... the memory issues are built up from within the main loop under NSLog(#"LOG ------------> Begin tile loop ");...
-(void)buildFromImage:(UIImage *)__image {
NSLog(#"LOG ------------> Begin Build ");
//if the __image is over 4096 width of 2992 height then we must resize it! (stop crashes ect)
if (__image.size.width > __image.size.height) {
if (__image.size.width > 4096) {
__image = [self resizeImage:__image toSize:CGSizeMake(4096, (__image.size.height * 4096 / __image.size.width))];
}
} else {
if (__image.size.height > 2992) {
__image = [self resizeImage:__image toSize:CGSizeMake((__image.size.width * 2992 / __image.size.height), 2992)];
}
}
//create preview image (if landscape, no more than 748 high... if portrait, no more than 1004 high) must keep scale
NSString *temp_archive_store = [[NSString alloc] initWithFormat:#"%#/%i-temp_imgdat.zip",NSTemporaryDirectory(),arc4random()];
NSString *temp_tile_store = [[NSString alloc] initWithFormat:#"%#/%i-temp_tilestore/",NSTemporaryDirectory(),arc4random()];
//create the temp dir for the tile store
[[NSFileManager defaultManager] createDirectoryAtPath:temp_tile_store withIntermediateDirectories:YES attributes:nil error:nil];
//create each tile and add it to the compressor once its made
//size of tile
CGSize tile_size = CGSizeMake(256, 256);
//the scales that we will be generating the tiles too
NSMutableArray *scales = [[NSMutableArray alloc] initWithObjects:[NSNumber numberWithInt:1000],[NSNumber numberWithInt:500],[NSNumber numberWithInt:250],[NSNumber numberWithInt:125], nil]; //scales to loop round over
NSLog(#"LOG ------------> Begin tile loop ");
#autoreleasepool {
//loop through the scales
for (NSNumber *scale in scales) {
//scale the image
UIImage *imageForScale = [self resizedImage:__image scale:[scale intValue]];
//calculate number of rows...
float rows = ceil(imageForScale.size.height/tile_size.height);
//calulate number of collumns
float cols = ceil(imageForScale.size.width/tile_size.width);
//loop through rows and cols
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
NSLog(#"LOG ------> Creating Tile (%i,%i,%i)",col,row,[scale intValue]);
//build name for tile...
NSString *tile_name = [NSString stringWithFormat:#"%#_%i_%i_%i.png",#"image",[scale intValue],col,row];
#autoreleasepool {
//build tile for this coordinate
UIImage *tile = [self tileForRow:row column:col size:tile_size image:imageForScale];
//convert image to png data
NSData *tile_data = UIImagePNGRepresentation(tile);
[tile_data writeToFile:[NSString stringWithFormat:#"%#%#",temp_tile_store,tile_name] atomically:YES];
}
}
}
}
}
}
Here are my resizing/cropping functions too as these could also be causing the issue..
-(UIImage *)resizeImage:(UIImage *)inImage toSize:(CGSize)scale {
#autoreleasepool {
CGImageRef inImageRef = [inImage CGImage];
CGColorSpaceRef clrRf = CGColorSpaceCreateDeviceRGB();
CGContextRef ctx = CGBitmapContextCreate(NULL, ceil(scale.width), ceil(scale.height), CGImageGetBitsPerComponent(inImageRef), CGImageGetBitsPerPixel(inImageRef)*ceil(scale.width), clrRf, kCGImageAlphaPremultipliedFirst );
CGColorSpaceRelease(clrRf);
CGContextDrawImage(ctx, CGRectMake(0, 0, scale.width, scale.height), inImageRef);
CGImageRef img = CGBitmapContextCreateImage(ctx);
UIImage *image = [[UIImage alloc] initWithCGImage:img scale:1 orientation:UIImageOrientationUp];
CGImageRelease(img);
CGContextRelease(ctx);
return image;
}
}
- (UIImage *)tileForRow: (int)row column: (int)col size: (CGSize)tileSize image: (UIImage*)inImage
{
#autoreleasepool {
//get the selected tile
CGRect subRect = CGRectMake(col*tileSize.width, row * tileSize.height, tileSize.width, tileSize.height);
CGImageRef inImageRef = [inImage CGImage];
CGImageRef tiledImage = CGImageCreateWithImageInRect(inImageRef, subRect);
UIImage *tileImage = [[UIImage alloc] initWithCGImage:tiledImage scale:1 orientation:UIImageOrientationUp];
CGImageRelease(tiledImage);
return tileImage;
}
}
Now I never use to be that good with memory management, so I did take the time to read up on it and also converted my project to ARC to see if that could address my issues (that was a while ago) but from the results i get after profiling it in instruments I must be doing something STUPIDLY wrong for the memory to leak as bad as it does but I just can't see what i'm doing wrong.
If anybody can point out anything I may be doing wrong it would be great!
Thanks
Liam
(let me know if you need more info)
I use "UIImage+Resize". Inside #autoreleasepool {} it works fine with ARC in a loop.
https://github.com/AliSoftware/UIImage-Resize
-(void)compress:(NSString *)fullPathToFile {
#autoreleasepool {
UIImage *fullImage = [[UIImage alloc] initWithContentsOfFile:fullPathToFile];
UIImage *compressedImage = [fullImage resizedImageByHeight:1024];
NSData *compressedData = UIImageJPEGRepresentation(compressedImage, 75.0);
[compressedData writeToFile:fullPathToFile atomically:NO];
}
}

App crashes on drawing of UILabel - NSString is a zombie

I'm working on an iPad app that has a slider that is used to scroll through data. When scrolling, a map is displayed and the data is updated. The problem is, if you scroll fast enough (or somehow trigger the race condition), the app crashes on accessing a zombie NSString. I've been able to track it down in the Profiler and found this:
Event Type RefCt Timestamp Size Responsible Library Responsible Caller
Malloc 1 01:55.166.466 16 Foundation -[NSPlaceholderString initWithFormat:locale:arguments:]
Autorelease <null> 01:55.166.472 0 Foundation +[NSString stringWithFormat:]
CFRetain 2 01:55.166.473 0 My Program -[StateView updateVotes:]
CFRetain 3 01:55.166.476 0 UIKit -[UILabel setText:]
CFRelease 2 01:55.166.504 0 My Program -[StateView updateVotes:]
CFRelease 1 01:55.177.661 0 Foundation -[NSAutoreleasePool release]
CFRelease 0 01:55.439.090 0 UIKit -[UILabel setText:]
Zombie -1 01:55.439.109 0 UIKit -[NSString(UIStringDrawing) drawAtPoint:forWidth:withFont:lineBreakMode:letterSpacing:includeEmoji:]
I'm using ARC on iOS5, so I'm not in control of the retain/release at all. Even if I was, looking at the above, it is correct. The problem seems to be a race condition between the drawing function and the UILabel string actually changing. The UILabel releases the first string, as a new one has been set, but the drawing function is holding a reference to it somehow, but did not retain it.
As a note, I have not modified the UILabel in any way.
Any ideas?
--- Code added as update:
Slider update:
-(void)sliderValueChanged:(UISlider *)slider {
float position = slider.value - 1790.0f;
int year;
if(position <= 0.0f) {
year = 1789;
} else {
year = 1792 + (floor(position / 4.0f)*4);
}
[self setYear:year];
}
setYear:
-(void)setYear:(int)year {
if (year == currentYear) {
// year didn't change, so don't do anything
return;
}
[yearLabel setText:[[NSString alloc] initWithFormat:#"%i", year]];
currentYear = year;
[self getMapForYear:year];
}
getMapForYear:
-(void) getMapForYear:(int)year {
[self setToMap:[historicalData objectForKey:[NSNumber numberWithInt:year]];
}
setToMap:
-(void) setToMap:(HistoricalMap *)map {
// Label the map
for (State *state in [map states]) {
[mapController setVotes:[state votes] forState:[state abbreviation]];
}
}
setVotes:forState:
-(void)setVotes:(NSNumber *)votes forState:(NSString *)stateAbbreviation {
StateView *state = [states objectForKey:stateAbbreviation];
if (state == nil) {
NSLog(#"Invalid State Votes -- %#", stateAbbreviation);
return;
}
[state updateVotes:votes];
[state setNeedsDisplay];
}
updateVotes:
-(void)updateVotes:(NSNumber *)newVotes {
[self setVotes:newVotes];
NSString *voteString = [[NSString alloc] initWithFormat:#"%#", newVotes];
[voteLabel setText:voteString];
if ([newVotes isEqual:[NSNumber numberWithInt:0]]) {
[[self voteLabel] setHidden:YES];
[[self stateAbbreviationLabel] setHidden:YES];
} else {
[[self stateAbbreviationLabel] setHidden:NO];
[[self voteLabel] setHidden:NO];
}
}
I think you are attempting to do far too much during the slider's movement. Creating and executing core data fetch requests alone would seem to be overkill, let alone updating the entire GUI and a screenful of labels. Have you tested the performance of this on a device?
It could be worth profiling these sections of code and seeing where the time is spent. You could look at caching the fetch requests or the results, for example, or you may have to resort to updating only when the slider has stopped, or only for every n increments along the path.
You havw several memory-leaks with NSString:
[yearLabel setText:[[NSString alloc] initWithFormat:#"%i", year]]; // leak
Create string with stringWithFormat method instead
[yearLabel setText:[NSString stringWithFormat:#"%i", year]];
[NSString stringWithFormat: **is the best way formatting the string than any other..**

CaptureScreen in Objective-C using OpenGL on an IMac

I have a multidisplay system, 27 inch (2560 x 1440) and Apple Cinema Display (1920 x 1200) with ATI Radeon HD 5750 1024 MB graphics card. I used to be able to capture screen shots with my previous iMac with a Nvidia card, also multidisplay systems. Now I get an OpenGL error.
This GDB was configured as "x86_64-apple-darwin".tty /dev/ttys001
[Switching to process 28434 thread 0x0] 2011-08-20 19:07:42.040
DetectObjectColor[28434:c03] invalid fullscreen drawable 2011-08-20
19:07:42.043 DetectObjectColor[28434:c03] * Assertion failure in
-[OpenGLScreenReader readPartialScreenToBuffer:bufferBaseAddress:],
/Documents/Personal/DetectObjectColor/OpenGLScreenReader.m:230
2011-08-20 19:07:42.043 DetectObjectColor[28434:c03] * Terminating
app due to uncaught exception 'NSInternalInconsistencyException',
reason: 'OpenGL error 0x0506'
I call this from my main program:
OpenGLScreenReader *mOpenGLScreenReader;
mOpenGLScreenReader = [[OpenGLScreenReader alloc] init];
[mOpenGLScreenReader readRectScreen:CGRectMake(570, 265, 35, 800)];
This is my init method
-(id) init
{
if (self = [super init])
{
// Create a full-screen OpenGL graphics context
// Specify attributes of the GL graphics context
NSOpenGLPixelFormatAttribute attributes[] = {
NSOpenGLPFANoRecovery,
NSOpenGLPFAFullScreen,
NSOpenGLPFAScreenMask,
CGDisplayIDToOpenGLDisplayMask(kCGDirectMainDisplay),
(NSOpenGLPixelFormatAttribute) 0
};
NSOpenGLPixelFormat *glPixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:attributes];
if (!glPixelFormat)
{
return nil;
}
// Create OpenGL context used to render
mGLContext = [[[NSOpenGLContext alloc] initWithFormat:glPixelFormat shareContext:nil] autorelease];
// Cleanup, pixel format object no longer needed
[glPixelFormat release];
if (!mGLContext)
{
[self release];
return nil;
}
[mGLContext retain];
// Set our context as the current OpenGL context
[mGLContext makeCurrentContext];
// Set full-screen mode
[mGLContext setFullScreen];
NSRect mainScreenRect = [[NSScreen mainScreen] frame];
mWidth = mainScreenRect.size.width;
mHeight = mainScreenRect.size.height;
mByteWidth = mWidth * 4; // Assume 4 bytes/pixel for now
mByteWidth = (mByteWidth + 3) & ~3; // Align to 4 bytes
mData = malloc(mByteWidth * mHeight);
NSAssert( mData != 0, #"malloc failed");
}
return self;
}
This is my readRectScreen method which is giving me the error on OpenGL when it executes the readPartialScreenToBuffer method
- (void) readRectScreen:(CGRect) srcRect
{
mWidth = srcRect.size.width;
mHeight = srcRect.size.height;
mByteWidth = mWidth * 4; // Assume 4 bytes/pixel for now
mByteWidth = (mByteWidth + 3) & ~3; // Align to 4 bytes
mData = malloc(mByteWidth * mHeight);
[self readPartialScreenToBuffer:srcRect bufferBaseAddress: mData];
}
- (void) readPartialScreenToBuffer: (CGRect) srcRect bufferBaseAddress: (void *) baseAddress
{
// select front buffer as our source for pixel data
GLint width, height;
width = srcRect.size.width;
height = srcRect.size.height;
glReadBuffer(GL_FRONT);
//Read OpenGL context pixels directly.
// For extra safety, save & restore OpenGL states that are changed
glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT);
glPixelStorei(GL_PACK_ALIGNMENT, 4); /* Force 4-byte alignment */
glPixelStorei(GL_PACK_ROW_LENGTH, 0);
glPixelStorei(GL_PACK_SKIP_ROWS, 0);
glPixelStorei(GL_PACK_SKIP_PIXELS, 0);
//Read a block of pixels from the frame buffer
glReadPixels((GLint)srcRect.origin.x, (GLint)srcRect.origin.y, width, height, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV,baseAddress);
glPopClientAttrib();
//Check for OpenGL errors
GLenum theError = GL_NO_ERROR;
theError = glGetError();
NSAssert1( theError == GL_NO_ERROR, #"OpenGL error 0x%04X", theError);
}
Can anybody please help... I am totally lost as to where the error might be.
I guess your new computer has Mac OS X 10.7 (Lion) installed. Lion does not allow this method of screen capture (reading the front buffer) anymore. Applications must migrate to CGDisplayCaptureImage() API, which was introduced in 10.6.
Your issue seems to be, that you don't get/have a valid OpenGL context. But that's not your real problem:
OpenGL is a drawing/rendering library. glReadPixels is meant to read back the image generated by your program. OpenGL is not a general purpose graphics API (though some/many people confuse it for that).
For some time one could exploit the side effects between OpenGL contexts, windows and framebuffers to take screenshots using glReadPixels. On modern systems with compositing window managers this no longer works!
You're barking up the wrong tree, sorry.