App is crashing with EXC_BAD_ACCESS on background - iphone

i setted NSString *oldChat in the header file like this:
#interface CTFChatViewController : UIViewController {
NSString *oldChat;
}
- (void)updateChat;
#property (nonatomic, retain) NSString *oldChat;
#end
and then i used it:
- (void)updateChat
{
NSString *chat = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://theshay.byethost7.com/chat.php"] encoding:NSUTF8StringEncoding error:nil];
if (![chat isEqual:oldChat])
{
[webView loadHTMLString:chat baseURL:nil];
oldChat = chat;
}
[self performSelectorInBackground:#selector(updateChat) withObject:nil];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
NSString *chat = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://theshay.byethost7.com/chat.php"] encoding:NSUTF8StringEncoding error:nil];
oldChat = chat;
[webView loadHTMLString:chat baseURL:nil];
[self performSelectorInBackground:#selector(updateChat) withObject:nil];
}
App crashed on if (![chat isEqual:oldChat]) with EXC_BAD_ACCESS error.
why it crashed ?
(XCode 4.5.2, iPhone Simulator 6.0, Base SDK 6.0)

oldChat is autorelease object. Retain it and use isEqualToString for string comparison.
NSString *chat = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://theshay.byethost7.com/chat.php"] encoding:NSUTF8StringEncoding error:nil];
oldChat = chat;
[oldChat retain];

You have to check your NSString is equal or not using isEqualToString: method. Your code should be like this
if (![chat isEqualToString:oldChat]){
//Do something
}

Related

UIWebView Not loading

I am having a problem where UrlDisplay isn't displaying any data. UrlDisplay is located at the bottom of my .M. What I am doing is requesting a website collecting a few urls specific to the users request. Then setting up UiWebViews for them to navigate though is there any way to split a single UiWebView, or is this the best way to do it? (My sample is only collecting one website and trying to set one website to a UIWebView)I am not sure of why this is happening Everything in the .h is connected properly to the storyboard. Thanks for the help in advanced for any feed back!
.H
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
#property (weak, nonatomic) IBOutlet UIWebView *UrlDisplay;
#end
.M
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize UrlDisplay;
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *website = [NSURL URLWithString:#"www.Google.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:website];
NSURLResponse* response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//storing data in a string
NSString *myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSArray *newString = [myString componentsSeparatedByString:#"\n"];
// Do any additional setup after loading the view, typically from a nib.
NSMutableString *curLineNum;
NSString *curLine;
NSMutableArray *URL =[[NSMutableArray alloc]init];
int i;
for (i = 0; i <[newString count]; i++) {
curLine = [newString objectAtIndex:i];
if ([curLine rangeOfString:#"Start Here"].location != NSNotFound) {
NSScanner *scanner = [NSScanner scannerWithString:curLine];
[scanner scanUpToString:#"Start Here" intoString:NULL];
[scanner setScanLocation:([scanner scanLocation]) + 16];
[scanner scanUpToString:#"End Here" intoString:&curLineNum];
[Url addObject:curLineNum];
}
}
NSURL *preWebsite = [NSURL URLWithString:[Url objectAtIndex:0]];
NSURLRequest *preRequest = [NSURLRequest requestWithURL:preWebsite];
[UrlDisplay loadRequest:preRequest];
//NSLog(#"%#",myString);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
the method URLWithString always expecting full URL path including URL scheme. In your case URL scheme is missing. Try this.
NSURL *website = [NSURL URLWithString:#"http://www.Google.com"];

Links inside Pdf on Webview are not opening in a browser in iPhone

I have parsed urls of pdfs and showing pdf on a webView, but my Links inside webviews are not opening in a browser.i have not used CGPDFDocument. my code is simple :). can anyone help me out.i have seen many similar questions but all are using Quartz.
code :-
#class AppDelegate_iPhone;
#interface PdfShowViewController : UIViewController<UIWebViewDelegate> {
IBOutlet UIWebView *pdfWebview;
AppDelegate_iPhone *appDelegate;
NSMutableData *receivedData;
IBOutlet UIActivityIndicatorView *myIndicator;
IBOutlet UIProgressView *progress;
NSURLRequest* DownloadRequest;
NSURLConnection* DownloadConnection;
long long bytesReceived;
long long expectedBytes;
IBOutlet UILabel *downloadLabel;
}
#property (nonatomic,retain) IBOutlet UILabel *downloadLabel;
#property (nonatomic,retain) IBOutlet UIWebView *pdfWebview;
#property (nonatomic,retain) IBOutlet UIActivityIndicatorView *myIndicator;
#property (nonatomic,retain) IBOutlet UIProgressView *progress;
#property (nonatomic,retain) NSMutableData *receivedData;
#property (nonatomic, readonly, retain) NSURLRequest* DownloadRequest;
#property (nonatomic, readonly, retain) NSURLConnection* DownloadConnection;
#property (nonatomic, retain, readwrite) NSURL *openURL;
-(IBAction)onTapBack;
#end
#implementation PdfShowViewController
#synthesize pdfWebview,myIndicator,progress,receivedData,DownloadRequest,DownloadConnection,downloadLabel,openURL;
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData appendData:data];
unsigned char byteBuffer[[receivedData length]];
[receivedData getBytes:byteBuffer];
NSLog(#"Data === %ld",receivedData);
NSInteger receivedLen = [data length];
bytesReceived = (bytesReceived + receivedLen);
NSLog(#"received Bytes == %f",bytesReceived);
if(expectedBytes != NSURLResponseUnknownLength)
{
NSLog(#"Expected Bytes in if == %f",expectedBytes);
NSLog(#"received Bytes in if == %f",bytesReceived);
float value = ((float) (bytesReceived *100/expectedBytes))/100;
NSLog(#"Value == %f",value);
progress.progress=value;
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[connection release];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
expectedBytes = [response expectedContentLength];
NSLog(#"%f",expectedBytes);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[myIndicator stopAnimating];
[myIndicator removeFromSuperview];
[progress setHidden:YES];
[downloadLabel setHidden:YES];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:#"iPhonePdf.pdf"];
unsigned char byteBuffer[[receivedData length]];
[receivedData getBytes:byteBuffer];
[self.receivedData writeToFile:pdfPath atomically:YES];
[DownloadConnection release];
//Now create Request for the file that was saved in your documents folder
NSURL *url = [NSURL fileURLWithPath:pdfPath];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[pdfWebview setScalesPageToFit:YES];
[pdfWebview loadRequest:requestObj];
}
-(BOOL)webView:(UIWebView *)webView1 shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSURL *requestURL = [request URL];
if(navigationType==UIWebViewNavigationTypeLinkClicked)
{
[[UIApplication sharedApplication] openURL:requestURL];
return NO;
}
else
{
return YES;
}
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
pdfWebview.delegate = self;
appDelegate = (AppDelegate_iPhone *)[[UIApplication sharedApplication] delegate];
[downloadLabel setText:#"Downloading..."];
[downloadLabel setHidden:NO];
[myIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
myIndicator.hidesWhenStopped = YES;
[myIndicator startAnimating];
// NSString *urlString = [appDelegate.currentBookPressed stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSString *urlString = [appDelegate.currentBookPressed stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// NSLog(#"The Url Stirng=======%#",urlString);
NSURL *targetURL = [NSURL URLWithString:urlString];
//NSLog(#"Trageted String ------======++++++++%#",targetURL);
DownloadRequest = [NSURLRequest requestWithURL:targetURL cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:1200.0];
DownloadConnection = [[NSURLConnection alloc] initWithRequest:DownloadRequest delegate:self];
if (DownloadConnection) {
receivedData = [[NSMutableData data]retain];
}
[pdfWebview setScalesPageToFit:YES];
[pdfWebview loadRequest:DownloadRequest];
}
-(IBAction)onTapBack
{
[self dismissModalViewControllerAnimated:YES];
}
#end
here is the link which i am trying to open but not opening :-
No, links inside pdf files loaded in a UIWebView won't open when you tap them by default.
You can go the hard way and parse the links out using Quartz as is shown in this other post I answered.
Or, instead of loading a pdf, can you convert the content you are loading to an html file instead? That would be easier, and the links should work then.
You have to use below delegate method
-(BOOL)webView:(UIWebView *)webView1 shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSURL *requestURL = [request URL] ;
if(navigationType==UIWebViewNavigationTypeLinkClicked)
{
[[UIApplication sharedApplication] openURL:requestURL];
return NO;
}
else
{
return YES;
}
}

Trouble using a custom NSObject class to simplify repetitive code in iPhone app

I am trying to store a REST connection model in a single object so that I don't keep having to use it over and over again. Here is the model I created:
//RestModel.h
#import "ASIHTTPRequest.h"
#interface RestModel : NSObject{
NSString* _baseUrl;
NSString* _modelUrl;
}
#property (nonatomic, retain) NSString* modelUrl;
- (id)initWithModel:(NSString*)model;
- (NSDictionary*)getById:(NSInteger*)ident;
- (NSDictionary*)getAll;
#end
//RestModel.m
#import "RestModel.h"
#implementation RestModel
#synthesize modelUrl = _modelUrl;
- (id)init
{
self = [super init];
if (self) {
_baseUrl = #"http://myRESTurl.com";
}
return self;
}
- (id)initWithModel:(NSString*)model
{
self = [super init];
if (self) {
_baseUrl = #"http://myRESTurl.com";
self.modelUrl = [NSString stringWithFormat:#"%#/%#/", _baseUrl, model];
}
return self;
}
- (NSDictionary*)HTTPRequest:(NSURL*)url
{
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous];
NSError *error = [request error];
if(!error){
NSData *responseData = [request responseData];
NSString *errorDesc = nil;
NSPropertyListFormat format;
[error release];
[request release];
return (NSDictionary*)[NSPropertyListSerialization propertyListFromData:responseData mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&errorDesc];
}else{
NSLog(#"%#", error);
return nil;
}
}
- (NSDictionary*)getById:(NSInteger*)ident
{
NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:#"%#/%#", self.modelUrl, ident]];
return [self HTTPRequest:url];
}
- (NSDictionary*)getAll
{
NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:#"%#", self.modelUrl]];
return [self HTTPRequest:url];
}
- (void)dealloc
{
[_modelUrl release];
// [_responseData release];
// [_responseDict release];
[super dealloc];
}
#end
Edit: Now it isn't crashing, but my local NSDictionary has a count of 0. I'm calling the following in -viewDidLoad in my controller:
RestModel* rm = [[RestModel alloc] initWithModel:#"user"];
self.dict = [rm getAll];
[rm release];
I planted NSLog of [self.dict count] throughout the controller. It is always 0. The RestModel rm is called, the functions are called (again more NSLogs), but no data. Any ideas?
[error release];
[request release];
Those should be auto-released objects, as you got them by convenience methods, so releasing them explicitly will make your application crash.
NSInteger isn't an object so it isn't necessary to pass it using NSInteger * and certainly you do not want to use the %# format specifier. Instead try this:
- (NSDictionary*)getById:(NSInteger)ident
{
NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:#"%#/%d", self.modelUrl, ident]];
return [self HTTPRequest:url];
}

How to load table with some default image till it get the original image from internet iPhone?

I have a uitableview which stores one image in one cell. Its image get loaded from internet. The problem is the application get slow till its image get loaded from internet. So I want to put a mechanism that it first get loaded with a default image and when it gets the original then the default image will be replaced by the original one.
Give me any tutorial or any sample code for it.
Thanks in advance.
Get your image trough some other thread .... and use notification or delegate to keep track of any change in image download ... suppose you are using notification .... then in class which you set as observer for that notification reload the data of tableView .... so your table image will get updated where there was so default image .... for more detail lets take an example ..... Make a operation class to downloading the image we call it thumb .... In this example I make 2 classes
1. PhotoGalleryVC which shows a list of thumbs and some detail of each thumb and
2. LoadGalleryThumbOp [Op = operation] downloads thumbs and post notification when done
#protocol LoadGalleryThumbDelegate;
#interface LoadGalleryThumbOp : NSObject{
NSIndexPath* indexPathInTableView;
id <LoadGalleryThumbDelegate> delegate;
NSMutableData *activeDownload;
NSURLConnection *imageConnection;
NSString * documentPath;
BOOL imageDownload;
}
#property (nonatomic, assign) NSIndexPath* indexPathInTableView;
#property (nonatomic, retain) NSMutableData *activeDownload;
#property (nonatomic, retain) NSURLConnection *imageConnection;
#property (nonatomic, assign) id <LoadGalleryThumbDelegate> delegate;
#property (nonatomic, retain) NSString * documentPath;
#property (nonatomic) BOOL imageDownload;
- (void)startDownload;
- (void)cancelDownload;
- (void) persistData:(NSData*) data;
#end
#protocol LoadGalleryThumbDelegate
- (void)appImageDidLoad:(NSIndexPath *)indexPath;
#end
in LoadGalleryThumbOp.m do it as
#implementation LoadGalleryThumbOp
#synthesize year;
#synthesize indexPathInTableView;
#synthesize delegate;
#synthesize activeDownload;
#synthesize imageConnection,documentPath,imageDownload;
#pragma mark
- (void)startDownload
{
self.imageDownload = YES;
self.activeDownload = [NSMutableData data];
NSFileManager* fm = [NSFileManager defaultManager];
NSString* galleryDocumentPath = [self.documentPath stringByAppendingPathComponent:[NSString stringWithFormat:#"images/thumb.jpg"]];
if ([fm fileExistsAtPath:galleryDocumentPath])
{
UIImage *image = [[UIImage alloc] initWithContentsOfFile:galleryDocumentPath ];
self.gallery.thumpImage = image;
self.activeDownload = nil;
[image release];
self.imageConnection = nil;
[delegate appImageDidLoad:self.indexPathInTableView];
}
else {
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:
[NSURLRequest requestWithURL:
[NSURL URLWithString:#error yourImageUrl]] delegate:self];
self.imageConnection = conn;
[conn release];
}
}
- (void)cancelDownload
{
[self.imageConnection cancel];
self.imageConnection = nil;
self.activeDownload = nil;
}
#pragma mark -
#pragma mark Download support (NSURLConnectionDelegate)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.activeDownload appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
self.activeDownload = nil;
self.imageConnection = nil;
self.imageDownload = NO;
[NSString stringWithFormat:#"images/thumb.jpg"]];
[delegate appImageDidLoad:self.indexPathInTableView];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[self persistData:self.activeDownload];
self.activeDownload = nil;
self.imageConnection = nil;
[delegate appImageDidLoad:self.indexPathInTableView];
}
- (void) persistData:(NSData*) data
{
NSFileManager* fm = [NSFileManager defaultManager];
NSString* galleryDocumentPath = [self.documentPath stringByAppendingPathComponent:[NSString stringWithFormat:#"images/thumb.jpg"]];
if ([[NSFileManager defaultManager] fileExistsAtPath:galleryDocumentPath])
{
NSError* err = nil;
[fm removeItemAtPath:galleryDocumentPath error:&err];
if (err)
NSLog(#"%s:%#",__FUNCTION__,err);
}
[fm createFileAtPath:galleryDocumentPath contents:data attributes:nil];
}
this class will download the image you wanted and will call its delegate when the image is download ..
Now comes its use part in PhotoGalleryVC use it like this
#interface PhotoGalleryVC : UIViewController <LoadGalleryThumbDelegate>{
IBOutlet UITableView* albumListTableView;
NSMutableDictionary *imageDownloadsInProgress;
NSArray* allThumbs;
}
#property (nonatomic, retain) NSMutableDictionary *imageDownloadsInProgress;
- (void)appImageDidLoad:(NSIndexPath *)indexPath;
#end
in .m part
- (void)viewDidLoad {
self.imageDownloadsInProgress = [NSMutableDictionary dictionary];
.....
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSFileManager* fm = [NSFileManager defaultManager];
NSString* galleryDocumentPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:#"Gallery/%#/images/thumb.jpg",[someObj.title stringByReplacingOccurrencesOfString:#" " withString:#"_" ]]];
//this above line is just make a seperate folder for each object and store thumbs of that object in that folder ... so make it unique some how
if (![fm fileExistsAtPath:galleryDocumentPath])
{
LoadGalleryThumbOp *galleryThumbDownloader = [imageDownloadsInProgress objectForKey:indexPath];
if (galleryThumbDownloader != nil && galleryThumbDownloader.imageDownload == NO)
{
[cell.activityIndicator stopAnimating];
cell.albumCoverImageView.image = [UIImage imageNamed:#"no_thumb.png"];
}
else {
[cell.activityIndicator startAnimating];
}
[self startIconDownload:temp forIndexPath:indexPath andYear:[NSString stringWithFormat:#"%d",selectedYear]];
}
else
{
[cell.activityIndicator stopAnimating];
cell.albumCoverImageView.image = [UIImage imageWithContentsOfFile:galleryDocumentPath];
}
return cell ;
}
//The following method see if there is already so downloader that is downloading same image then it simply do nothing else it create a downloader and start it
- (void)startIconDownload:(Gallery *)gallery forIndexPath:(NSIndexPath *)indexPath andYear:(NSString*)yr
{
LoadGalleryThumbOp *galleryThumbDownloader = [imageDownloadsInProgress objectForKey:indexPath];
if (galleryThumbDownloader == nil)
{
NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* nameWithoutSpace = [gallery.title stringByReplacingOccurrencesOfString:#" " withString:#"_" ];
NSString* galleryDocumentPath = [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:#"Gallery//%#",nameWithoutSpace]];
galleryThumbDownloader = [[LoadGalleryThumbOp alloc] init];
galleryThumbDownloader.documentPath = galleryDocumentPath;
galleryThumbDownloader.indexPathInTableView = indexPath;
galleryThumbDownloader.delegate = self;
[imageDownloadsInProgress setObject:galleryThumbDownloader forKey:indexPath];
[galleryThumbDownloader startDownload];
[galleryThumbDownloader release];
}
else if(galleryThumbDownloader.imageDownload == NO)
{
if (albumListTableView.dragging || albumListTableView.decelerating) {
[galleryThumbDownloader startDownload];
}
}
}
finally the method which is called when a particular image is downloaded
- (void)appImageDidLoad:(NSIndexPath *)indexPath
{
CustomCellPhotoGalary* cell = (CustomCellPhotoGalary*)[albumListTableView cellForRowAtIndexPath:indexPath];
LoadGalleryThumbOp *galleryThumbDownloader = [imageDownloadsInProgress objectForKey:indexPath];
if (galleryThumbDownloader != nil)
{
if (galleryThumbDownloader.imageDownload)
{
[cell.activityIndicator stopAnimating];
NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* nameWithoutSpace = [temp.title stringByReplacingOccurrencesOfString:#" " withString:#"_" ];
NSString* galleryDocumentPath = [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:#"Gallery/%#",nameWithoutSpace]];
cell.albumCoverImageView.image = [UIImage imageWithContentsOfFile:galleryDocumentPath];
//galleryThumbDownloader = nil;
}
else {
[cell.activityIndicator stopAnimating];
cell.albumCoverImageView.image = [UIImage imageNamed:#"no_thumb.png"];
[self startIconDownload:temp forIndexPath:indexPath andYear:[NSString stringWithFormat:#"%d",selectedYear]];
}
[albumListTableView reloadData];
}
}
woooh.....! thats a lot of code for one example
Note : I cut out so many line so this code may not work for u directly {there may be so many errors .. }, But i hope you get the main idea behind the scene ... :)
This sample code is great, It taught me a lot.
This uses the ASIHttpRequest framework, if you are going to use this technique, I recommend you use the latest version from here, because the version in the sample code is quite old now.
This sample code should help you with custom delegation of your cells etc.
As per above scenario, its always better to use LazyTableImages.
The best example given here

How to save data from multiple views of an iPhone app?

I'm making an app where I need to save the text in multiple views in the app when the app quits. I also need to be able to remove all of the data from just one of those views and when the app quits, it's possible not all of those views will have been created yet.
After reading this post I thought perhaps it would be good to use a singleton that manages my app data which loads in the data when it is first requested and saved it when the app quits. Then in each view where I need to save data I can just set it on the singleton.
I gave it a go but have run into some issues. At first I didn't synthesize the properties (as in the post I was using as a guide) but the compiler told me I needed to make getters and setters, so I did. Now when my applicationWIllTerminate: gets call the app crashes and the console says "Program received signal: “EXC_BAD_ACCESS”. kill quit".
Is anyone able to tell me what I'm doing wrong, or suggest a better approach to saving the data?
//SavedData.h
#import <Foundation/Foundation.h>
#define kFileName #"appData.plist"
#interface SavedData : NSObject {
NSString *information;
NSString *name;
NSString *email;
NSString *phone;
NSString *mobile;
}
#property(assign) NSString *information;
#property(assign) NSString *name;
#property(assign) NSString *email;
#property(assign) NSString *phone;
#property(assign) NSString *mobile;
+ (SavedData *)singleton;
+ (NSString *)dataFilePath;
+ (void)applicationWillTerminate:(NSNotification *)notification;
#end
//SavedData.m
#import "SavedData.h"
#implementation SavedData
#synthesize information;
#synthesize name;
#synthesize email;
#synthesize phone;
#synthesize mobile;
static SavedData * SavedData_Singleton = nil;
+ (SavedData *)singleton{
if (nil == SavedData_Singleton){
SavedData_Singleton = [[SavedData_Singleton alloc] init];
NSString *filePath = [self dataFilePath];
if([[NSFileManager defaultManager] fileExistsAtPath:filePath]){
NSMutableArray * array = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
information = [array objectAtIndex:0];
name = [array objectAtIndex:1];
email = [array objectAtIndex:2];
phone = [array objectAtIndex:3];
mobile = [array objectAtIndex:4];
[array release];
}
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(applicationWillTerminate:) name:UIApplicationWillTerminateNotification object:app];
}
return SavedData_Singleton;
}
+ (NSString *)dataFilePath{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *DocumentsDirectory = [paths objectAtIndex:0];
return [DocumentsDirectory stringByAppendingPathComponent:kFileName];
}
+ (void)applicationWillTerminate:(NSNotification *)notification{
NSLog(#"Application will terminate received");
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:information];
[array addObject:name];
[array addObject:email];
[array addObject:phone];
[array addObject:mobile];
[array writeToFile:[self dataFilePath] atomically:YES];
[array release];
}
#end
Then when I want to use it I do
myLabel.text = [SavedData singleton].information;
And when I change the field
[SavedData singleton].information = #"my string";
Any help will be very much appreciated!
You might want to change your properties to be (retain) instead of assign.
You might want to get the singleton header file I use. It is quite nice for me.
What is likely happening is that you load up your array from a file, and assign it to the property. But it is being autoreleased, and thus it doesn't exist anymore. So when you try to access the memory later, it crashes.
Further reading on memory management: http://www.cocoadev.com/index.pl?MemoryManagement