Thursday, March 3, 2011

Xcode Program received signal: “EXC_BAD_ACCESS”




Your Ad Here

Program received signal: “EXC_BAD_ACCESS”

This error occurs in device not simulator.

Possible Errors:
  • access protected or non-existent memory space as result of a bad pointer
  • access memory without alloc init
  • access memory after released object
  • remove the [object release] only if you don’t use alloc/copy/retain
  • trying to access release objects
  • illegal memory access
DebuggingAutorelease

http://www.cocoadev.com/index.pl?DebuggingAutorelease
This show you how to use Cocoa’s NSZombie debugging class and the command line “malloc_history” tool to find exactly what released object has been accessed in you code.
Running Instruments and checking for leaks will not help troubleshoot EXEC_BAD_ACCESS.

Debugging Techniques
http://www.cocoadev.com/index.pl?DebuggingTechniques

NSAssert() call to validate method parameters is to track and avoid passing nils set a breakpoint on objc_exception_throw.

iPhone Server Communication




Your Ad Here


We can communicate in many ways with server. One way is using JSON, this is explained as below:

 

1. Starting Communication

[[[NSURLConnection alloc] initWithRequest:[NSURLRequest requestWithURL:
[NSURL URLWithString:urlStr]] delegate:self startImmediately:YES] autorelease];
//urlStr is NSString ref
 
2. Start receiving data
- (void)connection:(NSURLConnection *)connection didReceiveResponse:
   (NSURLResponse *)response{
    [receivedData setLength:0];
}
//receivedData is NSMutableData ref
 
3. Get data in chunks

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [receivedData appendData:data];
}

4. After getting complete data
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
 
    // json data retrival complete    (received data is NSMutableData)
    if(receivedData == nil || [receivedData length] == 0){
  //handle error in getting response, may be no network
        [self showAlertViewWithTitle:@"No network" andMessage:@"Could not open the
   page, because internet connection was not found." andTag:0];
        return;
    }
 
    NSString *responseBody = [[[NSString alloc] initWithData:receivedData
             encoding:NSUTF8StringEncoding] autorelease];
    ////NSLog(responseBody);
    NSError *jsonParsingError = [[[NSError alloc] init] autorelease];
    NSDictionary * jsonData = [NSDictionary dictionaryWithJSONData:
          [responseBody dataUsingEncoding:NSUTF8StringEncoding]
                error:&jsonParsingError];
 
    NSDictionary *serverError = [jsonData objectForKey:@"error"]==[NSNull null]?
 nil:[jsonData objectForKey:@"error"];
 
    if(serverError==nil || [serverError count]==0){
        // no error found else
        NSDictionary *response = [jsonData objectForKey:@"response"]==[NSNull null]?
  nil:[jsonData objectForKey:@"response"];
        NSArray *array = [response objectForKey:@"array"]==[NSNull null]?nil:
  [response objectForKey:@"array"];
// I have left the code incomplete, its just for understanding
 
5. Check for null values
Never forget to check null values from JSON data as follows:
NSString *dataValue =  [[[array objectAtIndex:i] objectForKey:@"key"]==[NSNull null]?
                         @"0":[[array objectAtIndex:i] objectForKey:@"key"] intValue]; 
 
Please let me know if you require further explanation..

Changing UIView’s Coordinate System




Your Ad Here


Some times in our app we want to change the coordinate system of UIView, mostly when we change the orientation of iPhone like Landscape Right or left, So that time, coordinate system as well as appearance of UIView should also change, so here is the code to do that…

        application.statusBarHidden=YES;
       
        [application setStatusBarOrientation:UIInterfaceOrientationLandscapeRight animated:YES];
       
        myUIView = [[MyUIView alloc] initWithFrame:CGRectMake(0,0,480,320)]; //as now width and height is changed
       
        [window addSubview:myUIView];
       
        CGAffineTransform transform=CGAffineTransformIdentity;
        transform=CGAffineTransformRotate(transform, (90.0f*22.0f)/(180.0f*7.0f));
        transform=CGAffineTransformTranslate(transform, 80, 80);
        [myUIView setTransform:transform];

Now all your subview’s of myUIView will also get transformed. and you will get CGPoint’s of new coordinate system on touch events.

UIImageView AnimationImages Memory Leak Mistry Solved




Your Ad Here




UIImage Tips…




Your Ad Here






There are several things which we need to keep in mind when we use UIImage as follows:

1. UIImage has 4 class methods to create its autorelease instance and 3 instance methods to load image.

2. When you want to cache the image, so that it can be easily loaded in no time whenever required, you should use:

UIImage *tempImage=[UIImage imageNamed:"test.png"]; where test.png is the image which will get cached at the first time and will remain in the memory untill app exits. But this should be used only when the image is less in memory size, otherwise your app will have less real and virtual memory for further use. This returns autorelease instance of UIImage that means you do not need to care about its release.

3. When you want to load the big memory sized images you should use:
UIImage *tempImage=[UIImage imageWithContentOfFile:[[NSBundle mainBundle] pathForResource:@”test” ofType:@”png”]];

this will not cache the image in the memory for the next time use i.e. when you again load this image this will be loaded from file.

4. When you don’t want autorelease instance i.e you want to manage its alloc free things on your own you should use:
UIImage *tempImage=[[UIImage alloc] initWithContentOfFile:[[NSBundle mainBundle] pathForResource:@”test” ofType:@”png”]];

but you have to release it when you are done with it as follows:
[tempImage release];

5. Whenever you set the UIImage’s instance to UIImageView’s image property, the retain count of UIImage’s instance increases by 1. So never forget to nil the UIImageView’s image property when you are done with it otherwise the UIImage will remain in the virtual memory and will leak.
Example:

UIImageView *imgView=[[UIImageView alloc] initWithImage:tempImage];
//now tempImage’s retain count will get increase by one. So nil the imgView’s image property whenever you are done with tempImage like this:
imgView.image=nil;

The difference b/w autorelease and normal instance is that we have to release the normal instance by calling release method to free up the memory

Objective C class: Simple Image Cache singleton




Your Ad Here


While working on an iPhone application which makes use of remote data and remote image assets, I realised I needed an object that could quickly and easily cache remote images in the app’s local sandboxed “Documents” folder. To be honest, I kind of feel like I reinvented someone’s wheel here, but I got exactly what I wanted – a small class (singleton) that provides full remote image (not limited to images though) caching within the sandboxed environment on an iPhone.

The class is implemented as a singleton since I can’t imagine one would want multiple storage caches running around interfering with each other.

ImageCache.h

//
//  ImageCache.h
//
//  Created by Tariq Mohammad on 03/03/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import 


@interface ImageCache : NSObject 
{
 NSString *documentsDirectory;
 NSString *cacheFileUrl;
 NSMutableDictionary *dictCache;
}

@property (nonatomic, retain) NSDictionary *dictCache;

+ (ImageCache*) instance;

- (BOOL) isRemoteFileCached:(NSString*)url;
- (NSData*) getCachedRemoteFile:(NSString*)url;
- (BOOL) addRemoteFileToCache:(NSString*)url withData:(NSData*)data;

@end
ImageCache.m

//
//  ImageCache.m//
//  Created by Tariq Mohammad on 03/03/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ImageCache.h"

#define kDefaultCacheFile @"imagecache.plist"

//////////////////////////////////////////////////////////////////////////////////////////////////

@interface ImageCache (private)
- (NSString*) makeKeyFromUrl:(NSString*)url;
@end//private ImageCache interface

//////////////////////////////////////////////////////////////////////////////////////////////////

static ImageCache *sharedInstance = nil;

//////////////////////////////////////////////////////////////////////////////////////////////////

@implementation ImageCache
@synthesize dictCache;

////////////////////////////////////////////////////////////////////////////////

- (id)init
{
 if ( (self = [super init]) )
 {
  
  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  
  documentsDirectory = [paths objectAtIndex:0];
  
  // the path to the cache map
  cacheFileUrl = [documentsDirectory stringByAppendingPathComponent:kDefaultCacheFile];
  [cacheFileUrl retain];

  dictCache = [[NSDictionary alloc] initWithContentsOfFile:cacheFileUrl];
  
  if ( dictCache == nil )
  {
   dictCache = [[NSMutableDictionary alloc] init];
  }
 }
 
 return self;
}

////////////////////////////////////////////////////////////////////////////////

- (void)dealloc
{
 [cacheFileUrl release];
 [dictCache release]
 [super dealloc];
}

////////////////////////////////////////////////////////////////////////////////

+ (ImageCache*) instance
{
 @synchronized(self)
 {
  if ( sharedInstance == nil )
  {
   sharedInstance = [[ImageCache alloc] init];
  }
 }
 return sharedInstance;
}

////////////////////////////////////////////////////////////////////////////////

- (BOOL) isRemoteFileCached:(NSString*)url
{
 NSString *imageFilename = [dictCache valueForKey:[self makeKeyFromUrl:url]];
 
 return (imageFilename != nil);
}

////////////////////////////////////////////////////////////////////////////////

- (NSData*) getCachedRemoteFile:(NSString*)url
{
 NSString *imageFilename = [dictCache valueForKey:[self makeKeyFromUrl:url]];
 NSData *data = nil;
 
 if ( imageFilename != nil )
 {
  data = [NSData dataWithContentsOfFile:imageFilename];
 }
 
 return data;
}

////////////////////////////////////////////////////////////////////////////////

- (BOOL) addRemoteFileToCache:(NSString*)url withData:(NSData*)data
{
 BOOL result = NO;
 NSString *imageFilename = [url lastPathComponent];
 
 if ( imageFilename != nil )
 {
  // the path to the cached image file
  NSString *cachedImageFileUrl = [documentsDirectory stringByAppendingPathComponent:imageFilename];

  result = [data writeToFile:cachedImageFileUrl atomically:YES];
  
  if ( result == YES )
  {
   // add the cached file to the dictionary
   [dictCache setValue:cachedImageFileUrl forKey:[self makeKeyFromUrl:url]];
   [dictCache writeToFile:cacheFileUrl atomically:YES];
  }
 }
 
 return result;
}

////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark Private Methods

- (NSString*) makeKeyFromUrl:(NSString*)url
{
 NSString *key = [url stringByReplacingOccurrencesOfString:@"/" withString:@"."];

 key = [key stringByReplacingOccurrencesOfString:@":" withString:@"."];
 return key;
}

@end

Let me know if you find this useful, or have suggestions on improving it.

Friday, February 4, 2011

How To Play YouTube Videos Within an Application




Your Ad Here


Playing a video (of a supported file format) on the iPhone is very easy using the MPMoviePlayerController class. You just create an instance of the class and initialize it with the URL of the video. The controller plays the video in full screen mode and returns back to your application when it’s done.
However, if the URL of the video is recognized by the iPhone as a YouTube URL then the Apple URL Scheme mechanism kicks in and launches the YouTube app. In this scenario control will not return to your app after the video has played. (The behavior is equivalent of calling [UIApplication openURL:] with the video URL.)
One workaround is to use a UIWebView and load it with the video URL. The drawback with this approach is that the user will see the rather ugly YouTube mobile web site and has to find and tap on the link of the video to play it.

YouTube Mobile

Another, visually more appealing, option is to create a small UIWebView on your screen and load it with the YouTube embed code. The result is a small button like image that shows the YouTube play button above a screen image from the video. When the user taps the image, the iPhone video player opens in full screen mode as usual, and when the video is done control is returned back to this screen.

YouTube Video Embedded in iPhone App

Here’s the code:


  1. - (void)embedYouTube:(NSString*)url frame:(CGRect)frame {  
  2.  NSString* embedHTML = @"\ 
  3.     \ 
  4.  \ 
  5.  body {\ 
  6.  background-color: transparent;\ 
  7.  color: white;\ 
  8.  }\ 
  9.  \ 
  10.  \ 
  11.      
  12.  width=\"%0.0f\" height=\"%0.0f\">\ 
  13.     ";  
  14.  NSString* html = [NSString stringWithFormat:embedHTML, url, frame.size.width, frame.size.height];  
  15.  if(videoView == nil) {  
  16.    videoView = [[UIWebView alloc] initWithFrame:frame];  
  17.    [self.view addSubview:videoView];  
  18.  }  
  19.  [videoView loadHTMLString:html baseURL:nil];  
  20. }

 
Submit Express Inc.Search Engine Optimization Services