Save Text From UITextVIEW? - iphone

I'm having a problem : i can' find a way to save properly my UITextView in a NSString.
I have created 4 UITextViews and i want them to be saved in the same file.
Heres the code :
-(void)destinataireTextView {
self.destiView = [[[UITextView alloc] initWithFrame:CGRectMake(200, 160, 150, 120)] autorelease];
[self.view addSubview: self.destiView];
}
-(void)expediteurTextView {
self.expediView = [[[UITextView alloc] initWithFrame:CGRectMake(430, 200, 150, 120)] autorelease];
[self.view addSubview: self.expediView];
}
-(void)objetTextView {
self.objetView = [[[UITextView alloc] initWithFrame:CGRectMake(200, 295, 150, 120)] autorelease];
[self.view addSubview: self.objetView];
}
-(void)corpsTextView {
self.corpsView = [[[UITextView alloc] initWithFrame:CGRectMake(200, 335, 150, 120)] autorelease];
[self.view addSubview: self.corpsView];
}
-(void)viewDidLoad{
[super viewDidLoad];
[self destinataireTextView];
[self expediteurTextView];
[self objetTextView];
[self corpsTextView];
}
I've tried this piece of code :
-(void)viewDidLoad
[super viewDidLoad];
NSString *filePath = [self pathOfFile];
if ([[NSFileManager defaultManager]fileExistsAtPath:filePath]) {
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
desti.text = [array objectAtIndex:0];
[array release];
}
UIApplication *notif = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(applicationWillTermite:) name:UIApplicationWillTerminateNotification object:notif];
}
-(NSString *) pathOfFile{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentFolder = [paths objectAtIndex:0];
return [documentFolder stringByAppendingFormat:#"SaveData.plist"];
}
-(void)applicationWillTermite:(NSNotification *)notification{
NSMutableArray *save = [[NSMutableArray alloc] init];
[save addObject:field1.text];
[save writeToFile:[self pathOfFile]atomically:YES];
[save release];
}
I desperately need help.
Thx

You don't really give us much to go on. No error messages. No suggestion of what you've tried or where it failed.
My guess, however, is this line:
return [documentFolder stringByAppendingFormat:#"SaveData.plist"];
I think you probably mean:
return [documentFolder stringByAppendingPathComponent:#"SaveData.plist"];
Otherwise your filename will look something like /some/pathSaveData.plist, which, obviously, is not valid.

Related

Download Multiple images using Native functionality IOS

How to download multiple images and save it to the disk.
The Send request i'm using is below.
for(NSDictionary *image in [data objectForKey:#"Catalogues"])
{
NSString *imurl =[image objectForKey:#"Image_Path"];
NSLog(#"%#",imurl);
NSString *urlstring =imurl;
NSLog(#"demo %#",urlstring);
NSURL *mailurl =[NSURL URLWithString:urlstring];
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:mailurl];
NSOperationQueue *ques =[[NSOperationQueue alloc]init];
[NSURLConnection sendAsynchronousRequest:request queue:ques completionHandler:^(NSURLResponse *respo, NSData *data, NSError *err) {
UIImage *image = [UIImage imageWithData:data];
UIImageView *im = [[UIImageView alloc] initWithFrame:CGRectMake(50, 100, 150, 150)];
im.image = image;
[self.view addSubview:im];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#",documentsDirectory]
any native methods available for multiple images?
you can implement an AsyncImage class like this
in AsyncImage.h file
#import <UIKit/UIKit.h>
#interface AsyncImage : UIView
{
NSURLConnection* connection;
NSMutableData* data;
UIImageView *image;
UIActivityIndicatorView *scrollingWheel;
NSString *imgName;
}
-(void)loadImageFromString:(NSString*)url;
-(void)loadImageFromURL:(NSURL*)url;
-(void)setLocalImage:(UIImage *)localImage;
-(id) initWithFrame:(CGRect)frame;
-(NSString *)applicationDocumentsDirectory;
-(void)cancelConnection;
#end
in AsyncImage.m file
#import "AsyncImage.h"
#implementation AsyncImage
-(id)initWithFrame:(CGRect)frame
{
if ((self = [super initWithFrame:frame]))
{
scrollingWheel = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
float x = self.bounds.size.width/2;
float y = self.bounds.size.height/2;
scrollingWheel.center = CGPointMake(x, y);
scrollingWheel.hidesWhenStopped = YES;
[self addSubview:scrollingWheel];
self.clipsToBounds = YES;
}
return self;
}
-(void)loadImageFromString:(NSString*)url
{
[scrollingWheel startAnimating];
if (connection!=nil) {
[connection release];
connection = nil;
}
if (data!=nil) {
[data release];
data = nil;
}
if (image != nil) {
[image removeFromSuperview];
image = nil;
}
imgName = [[[url componentsSeparatedByString:#"/"] lastObject]retain];
// NSLog(#"imgName=%#",imgName);
NSString *imagePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:imgName];
// NSLog(#"imagePath=%#",imagePath);
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:imagePath] == NO)
{
NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60.0];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
} else {
UIImage *img = [[UIImage alloc]initWithContentsOfFile:imagePath];
image = [[[UIImageView alloc] initWithImage:img] autorelease];
image.contentMode = UIViewContentModeScaleToFill;
image.frame = self.bounds;
[self addSubview:image];
[scrollingWheel stopAnimating];
}
}
-(void)setLocalImage:(UIImage *)localImage
{
if (image != nil) {
[image removeFromSuperview];
image = nil;
}
image = [[[UIImageView alloc] initWithImage:localImage] autorelease];
image.contentMode = UIViewContentModeScaleToFill;
image.frame = self.bounds;
[self addSubview:image];
}
//for URL
-(void)loadImageFromURL:(NSURL*)url
{
[scrollingWheel startAnimating];
if (connection!=nil) {
[connection release];
connection = nil;
}
if (data!=nil) {
[data release];
data = nil;
}
if (image != nil) {
[image removeFromSuperview];
image = nil;
}
NSString *strurl=[NSString stringWithFormat:#"%#",url];
imgName = [[[strurl componentsSeparatedByString:#"/"] lastObject]retain];
NSString *imagePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:imgName];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:imagePath] == NO)
{
NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60.0];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
} else {
UIImage *img = [[UIImage alloc]initWithContentsOfFile:imagePath];
image = [[[UIImageView alloc] initWithImage:img] autorelease];
image.contentMode = UIViewContentModeScaleToFill;
image.frame = self.bounds;
[self addSubview:image];
[scrollingWheel stopAnimating];
}
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[data release];
data=nil;
[scrollingWheel stopAnimating];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
data = [[NSMutableData data] retain];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)dataObj
{
[data appendData:dataObj];
}
-(void) connectionDidFinishLoading:(NSURLConnection *)theConnection
{
[connection release];
connection=nil;
NSString *imagePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:imgName];
[data writeToFile:imagePath atomically:YES];
image = [[[UIImageView alloc] initWithImage:[UIImage imageWithData:data]] autorelease];
image.contentMode = UIViewContentModeScaleToFill;
image.frame = self.bounds;
[self addSubview:image];
[data release];
data=nil;
[scrollingWheel stopAnimating];
}
-(void)dealloc
{
[scrollingWheel release];
[super dealloc];
}
-(NSString *)applicationDocumentsDirectory
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}
-(void)cancelConnection
{
if (connection !=nil) {
[connection cancel];
connection=nil;
}
if(data!=nil){
[data release];
data=nil;
}
[scrollingWheel stopAnimating];
}
#end
and at your viewController.m you can import this class and call it like this
AsyncImage *imgBOD = [[AsyncImage alloc] initWithFrame:CGRectMake(10, 46, 70, 70)];
[imgBOD loadImageFromString:[dictData objectForKey:#"image_path"]];
[self.view addSubview:imgBOD];
There is no "native method" for this particular problem.
If you just want to save a list of images to disk, you can improve your approach by not creating UIImages in the first place, just treat the data as binary data and save to disk directly.
In order to maintain low memory foot-print, implement NSURLConnection's delegate methods, and write (append) the image data piece-wise to the destination file as the chunk data arrives in connection:didReceiveData:.
The latter will be best solved by creating a dedicated class which encapsulates NSURLConnection and other related states and is subclassed from NSOperation and employs the asynchronous style implementing NSURLConnection delegates.
You might consider a third party library, too. A warning though: almost all well-known third party network libraries will not let you easily write data in pieces to a file. Per default, they accumulate all received data into one NSMutableData object. That may increase your memory-foot print, since images may be large, and since you can start multiple connections at once.
Also, don't start more than two connections at once.

How do I keep the keyboard hidden when it's not wanted?

The app I'm working on allows the user both to read text and to compose text, using different buttons. My problem now is that on the screen for reading text, if the user taps inside the UITextView box used on the screen for writing text, the keyboard appears. The UITextView in this case is self.textView; I've put the keyboard notifications and the keyboardWillShow method inside if(self.textView) statements and then made sure to call [self.textView removeFromSuperView] and set self.textView = nil; at the beginning of the reading text methods, but the keyboard still appears when you tap the space where self.textView is set (programmatically, by the way, not using the IB).
What am I doing wrong?
Edit: Thanks for the answers, guys and gals, but still that darn keyboard keeps coming back, just like the cat in the song.... Here's my code. Forgive its length, please, if you can; if I've done something wonky I don't know where it is, and so I don't know what to leave out.
Here's viewDidLoad.
-(void)viewDidLoad {
[super viewDidLoad];
self.textView.editable=NO;
self.textView.userInteractionEnabled = NO;
UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(previousHaiku)];
swipeRight.numberOfTouchesRequired = 1;
swipeRight.direction = UISwipeGestureRecognizerDirectionRight;
[self.view addGestureRecognizer:swipeRight];
UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(nextHaiku)];
swipeLeft.numberOfTouchesRequired = 1;
swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
[self.view addGestureRecognizer:swipeLeft];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"gayHaiku.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path])
{
NSString *bundle = [[NSBundle mainBundle] pathForResource:#"gayHaiku" ofType:#"plist"];
[fileManager copyItemAtPath:bundle toPath: path error:&error];
}
self.gayHaiku = [[NSMutableArray alloc] initWithContentsOfFile: path];
[self nextHaiku];
}
Here's nextHaiku, the last method called in viewDidLoad -- this is the reading method.
-(void)nextHaiku
{
[self.view.layer removeAllAnimations];
[self.bar removeFromSuperview];
self.textToSave=#"";
self.haiku_text.text=#"";
[self.view viewWithTag:1].hidden = NO;
[self.view viewWithTag:3].hidden = NO;
int indexOfHaiku;
NSMutableArray *arrayOfHaikuSeen;
NSString *cat;
if (!self.selectedCategory) cat = #"Derfner";
else cat = self.selectedCategory;
NSArray *filteredArray;
if (cat==#"all")
{
filteredArray = self.gayHaiku;
indexOfHaiku = self.indxAll;
arrayOfHaikuSeen = self.theseAreDoneAll;
}
else
{
indexOfHaiku = (cat==#"user")?self.indxU:self.indxD;
arrayOfHaikuSeen = (cat==#"user")?self.theseAreDoneU:self.theseAreDoneD;
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"category == %#", cat];
filteredArray = [self.gayHaiku filteredArrayUsingPredicate:predicate];
}
int array_tot = [filteredArray count];
int sortingHat;
NSString *txt;
if (array_tot > 0)
{
if (indexOfHaiku == arrayOfHaikuSeen.count)
{
while (true)
{
sortingHat = (arc4random() % array_tot);
if (![arrayOfHaikuSeen containsObject:[filteredArray objectAtIndex:sortingHat]]) break;
}
txt = [[filteredArray objectAtIndex:sortingHat] valueForKey:#"quote"];
if (!arrayOfHaikuSeen || arrayOfHaikuSeen.count==array_tot)
{
arrayOfHaikuSeen = [[NSMutableArray alloc] init];
}
[arrayOfHaikuSeen addObject:[filteredArray objectAtIndex:sortingHat]];
indexOfHaiku = arrayOfHaikuSeen.count;
if (arrayOfHaikuSeen.count==filteredArray.count)
{
[arrayOfHaikuSeen removeAllObjects];
indexOfHaiku=0;
}
}
else
{
txt = [[arrayOfHaikuSeen objectAtIndex:indexOfHaiku] valueForKey:#"quote"];
indexOfHaiku += 1;
}
}
//Need to test to make sure it starts over once all 110 haiku have been seen.
CGSize dimensions = CGSizeMake(320, 400);
CGSize xySize = [txt sizeWithFont:[UIFont fontWithName:#"Helvetica" size:14.0] constrainedToSize:dimensions lineBreakMode:0];
self.haiku_text = [[UITextView alloc] initWithFrame:CGRectMake((320/2)-(xySize.width/2),200,320,200)];
self.haiku_text.font = [UIFont fontWithName:#"Helvetica Neue" size:14];
self.haiku_text.backgroundColor = [UIColor clearColor];
self.haiku_text.text=txt;
CATransition *transition = [CATransition animation];
transition.duration = 0.25;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionPush;
transition.subtype =kCATransitionFromRight;
transition.delegate = self;
[self.view.layer addAnimation:transition forKey:nil];
[self.view addSubview:self.haiku_text];
if (cat==#"user")
{
self.theseAreDoneU = arrayOfHaikuSeen;
self.indxU = indexOfHaiku;
}
else if (cat==#"all")
{
self.theseAreDoneAll = arrayOfHaikuSeen;
self.indxAll = indexOfHaiku;
}
else
{
self.theseAreDoneD = arrayOfHaikuSeen;
self.indxD = indexOfHaiku;
}
}
And here's the writing method.
-(void)userWritesHaiku
//Set up the screen.
[self clearScreen];
self.textView = [[UITextView alloc] initWithFrame:CGRectMake(20, 60, 280, 150)];
self.textView.delegate = self;
self.textView.returnKeyType = UIReturnKeyDefault;
self.textView.keyboardType = UIKeyboardTypeDefault;
self.textView.font = [UIFont fontWithName:#"Helvetica Neue" size:14];
self.textView.scrollEnabled = YES;
self.textView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
self.textView.userInteractionEnabled = YES;
self.textView.editable=YES;
self.textView.backgroundColor = [UIColor colorWithRed:217 green:147 blue:182 alpha:.5];
[self.view addSubview: self.textView];
[self loadNavBar:#"Compose"];
[self addLeftButton:#"Instructions" callingMethod:#"haikuInstructions"];
//If you've added text before calling haikuInstructions, when you return from haikuInstructions the textView window with the different background color AND the keyboard.
[self addRightButton:#"Done" callingMethod:#"userFinishedWritingHaiku"];
self.titulus.hidesBackButton=YES;
[self seeNavBar];
//Create and add the space for user to write.
[self createSpaceToWrite];
if (self.textToSave!=#"")
{
self.textView.text = self.textToSave;
}
[self.view addSubview:self.textView];
[self.textView becomeFirstResponder];
//Keyboard notifications.
if (self.textView)
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
}
try this
[self.textView setEditable:NO];
When the user taps on the reading button, I would just call
self.textView.userInteractionEnabled = NO;
and when you want them to edit it call
self.textView.userInteractionEnabled = YES;
Well, it turned out that the whole time there was a UITextView I'd created in the xib and forgotten about because it was hiding under the main view--when I decided to create the UITextView programmatically I didn't remember to delete the other one, because I couldn't see it, but it was there working its evil will the entire time. I finally figured this out after commenting out literally the entire code with the exception of [super viewDidLoad] and removing everything from the xib.

UIScrollView not updating and displaying properly

Im having problem in my UIscrollView,this is what I have done: Whenever a user picks an image (Multiple or Single) in camera roll thru a Imagepicker, I want to display it in my UIScrollView. I was able to display it, but when I go to the Imagepicker again then pick again an image,it doesnt update the UIScrollView, I tried putting my [self createScrollView] in my viewDidAppear but It recreates the UIScrollView but not update it, so the old images and new images are combined together. So I have put them in viewDidLoadbut It only update when I go to another View Controller then back again.
// My UIScrollView with thumbnail image
- (void) createScrollView {
self.slotBg = [[UIView alloc] initWithFrame:CGRectMake(43, 370, 300, 143)];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = self.slotBg.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor grayColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
[self.slotBg.layer insertSublayer:gradient atIndex:0];
[self.view addSubview:self.slotBg];
self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0f,0.0f,300.0f,134.0f)];
[slotBg addSubview:self.scrollView];
int row = 0;
int column = 0;
for(int i = 0; i < _thumbs.count; ++i) {
UIImage *thumb = [_thumbs objectAtIndex:i];
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(column*60+10, row*60+10, 60, 60);
[button setImage:thumb forState:UIControlStateNormal];
[button addTarget:self
action:#selector(buttonClicked:)
forControlEvents:UIControlEventTouchUpInside];
button.tag = i;
[scrollView addSubview:button];
if (column == 4) {
column = 0;
row++;
} else {
column++;
}
}
[scrollView setContentSize:CGSizeMake(330, (row+1) * 60 + 10)];
}
// in my viewDidLoad
- (void)viewDidLoad
{
for(int i = 0; i <= 100; i++)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"oneSlotImages%d.png", i]];
NSLog(#"savedImagePath=%#",savedImagePath);
if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
[self addImage:[UIImage imageWithContentsOfFile:savedImagePath]];
NSLog(#"file exists");
}
}
NSLog(#"Count : %d", [_images count]);
[self createScrollView];
}
EDIT:
- (void) viewDidLoad {
[self createScrollView];
[_thumbs removeAllObjects];
UIView *removeView;
for(int i = 0; i < _thumbs.count; ++i) {
while((removeView = [scrollView viewWithTag:i]) != nil) {
[removeView removeFromSuperview];
}
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"oneSlotImages%d.png", i]];
NSLog(#"savedImagePath=%#",savedImagePath);
if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
[self addImage:[UIImage imageWithContentsOfFile:savedImagePath]];
NSLog(#"file exists");
}
}
NSLog(#"Count : %d", [_images count]);
}
}
There are two points:
Check for your data source. If image has been saved correctly in your documents directory or not.
No need to create scroll view and its parent view again. Move below code from createScrollView to viewDidLoad. these view should be created only once.
self.slotBg = [[UIView alloc] initWithFrame:CGRectMake(43, 370, 300, 143)];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = self.slotBg.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor grayColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
[self.slotBg.layer insertSublayer:gradient atIndex:0];
[self.view addSubview:self.slotBg];
self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0f,0.0f,300.0f,134.0f)];
[slotBg addSubview:self.scrollView];
Now, from viewDidAppear, first update your _thumbs array (data source). Then call createScrollView function. Inside this function, first remove all the subviews using tag from UIScrollView. Add all the thumbs again as you have done. Then call [self setNeedsDisplay] before returning from createScrollView.

“EXC_BAD_ACCESS" signal received

i am beginner in iphone programming i am doing an app of photo gallery in which while scrolling the UITableView i am getting this exception in my device as Program received signal: “EXC_BAD_ACCESS”
can anyone pls help me tackle this problem...
enter cod[super viewDidLoad];
self.title=#"Back";
udf=[NSUserDefaults standardUserDefaults];
id_arr=[[NSMutableArray alloc]init];
descrip_arr=[[NSMutableArray alloc]init];
path_arr=[[NSMutableArray alloc]init];
count_arr=[[NSMutableArray alloc]init];
client = [[[ClientController alloc] init] autorelease];
r_m = [[[RequestMessage alloc]init] autorelease];
m_j = [[[Main_Json alloc]init] autorelease];
[r_m setServiceType:#"IMAGE"];
[r_m setParameter:#"sample string"];
NSString * json_string = [m_j returnJsonString:r_m:#"button"];
json_string=[json_string stringByAppendingFormat: #"\n"];
NSLog(#"Client is sending:%#", json_string);
//NSLog(json_string);
client.connect;
NSLog(#"client connecting........");
if([client isConnected])
{
NSString *flag = [client send:json_string];
if(![flag isEqualToString:#"success"])
{
NSLog(#"Before Alert_view");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:flag delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
return;
}
NSString *Var=[client receiveResponse];
//NSLog(#"TEST:%#",Var);
NSString *main_str=[Var stringByReplacingOccurrencesOfString:#"!#{}&" withString:#""];
//main_str=[Var stringByReplacingOccurrencesOfString:#"{\"serviceType\":\"ALLIMAGE\",\"parameters\":[[]]}" withString:#""];
NSLog(#"Split:%#",main_str);
js=[[JsontoObject alloc]sivajiTV_response:main_str];
e1=[[Event alloc]init];
NSLog(#"TEST1:%#",[udf objectForKey:#"id_value"]);
NSLog(#"TEST2:%#",[udf objectForKey:#"des_value"]);
NSLog(#"TEST3:%#",[udf objectForKey:#"path_value"]);
NSLog(#"TEST4:%#",[udf objectForKey:#"count_value"]);
id_arr=[[udf objectForKey:#"id_value"] componentsSeparatedByString:#","];
NSArray *descrip_arr1 =[[udf objectForKey:#"des_value"] componentsSeparatedByString:#","];
NSArray *path_arr1=[[udf objectForKey:#"path_value"] componentsSeparatedByString:#","];
count_arr=[[udf objectForKey:#"count_value"] componentsSeparatedByString:#","];
//NSLog(#"-------------");
//NSLog(#"STRING_ID2:%#",descrip_arr1);
//NSLog(#"STRING_ID3:%#",path_arr1);
//NSLog(#"-------------");
for (int i=0; i<[descrip_arr1 count]; i++) {
NSString *temp=[NSString stringWithFormat:#"%#",[descrip_arr1 objectAtIndex:i]];
//NSLog(#"STRING_test:%#",temp);
temp=[temp stringByReplacingOccurrencesOfString:#"\"" withString:#""];
//NSLog(#"STRING_test1:%#",temp);
[descrip_arr addObject:temp];
NSString *temp1=[NSString stringWithFormat:#"%#",[path_arr1 objectAtIndex:i]];
temp1=[temp1 stringByReplacingOccurrencesOfString:#"\"" withString:#""];
[path_arr addObject:temp1];
}
NSLog(#"------------------------------------------------------------------------------");
NSLog(#"STRING_ID1:%#",id_arr);
NSLog(#"STRING_ID2:%#",descrip_arr);
NSLog(#"STRING_ID3:%#",path_arr);
NSLog(#"STRING_ID4:%#",count_arr);
NSLog(#"------------------------------------------------------------------------------");
if([main_str isEqualToString: [NSNull null]])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:main_str delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
return;
}
}
else
{
UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:nil message:#"Connection not Found" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert1 show];
[alert1 release];
}
UILabel *lblTitle=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, 40)];
lblTitle.backgroundColor=[UIColor clearColor];
self.navigationItem.titleView=lblTitle;
toolbar=[[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 25)];
toolbar.barStyle=UIBarStyleBlackOpaque;
[self.view addSubview:toolbar];
UILabel *mylabel = [[UILabel alloc] initWithFrame:CGRectMake(250, 2, 60, 20)];
mylabel.backgroundColor=[UIColor clearColor];
mylabel.textColor = [UIColor whiteColor];
mylabel.text = #"Gallery";
[toolbar addSubview:mylabel];
myTableView.frame=CGRectMake(0,26, 320,430);
// myTableView.backgroundView=nil;
[self.view addSubview:myTableView];
//self.myTableView.separatorColor = [UIColor clearColor];
//UITableViewController *myTableViewController = [[UITableViewController alloc] initWithTableStyle:UITableViewStyleGrouped];
// UIToolBar *myToolBar = [[UIToolBar alloc]initWithFrame:CGRectMake(0, 15, 320, 10)];
// CGRect *toolBarFrame;
// toolBarFrame = CGMakeRect (0, 440, 320, 40);
// [toolBarFrame setFrame:toolBarFrame];
// [myTableViewController.view addSubView:toolBarFrame];
//viewController.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"movies.jpg"]];
//myTableView.rowHeight=120;
[self.view addSubview:myTableView];
//tempArray = [[NSArray alloc] initWithObjects:#"Sports",#"News",#"naturals1",#"live",nil];
//titleArray = [[NSArray alloc] initWithObjects:#"SA spinners made the difference: Sammy",#"Cabinet terminates ISRO’s deal",#"Hudson River Fish Evolve Toxic ",#"Hi Today Special News?",nil];
//SBJSON *json = [SBJSON new];
// json.humanReadable = YES;
//self.tableDataList = tempArray;
//self.myTableView.backgroundColor = [UIColor clearColor];
//create new uiview with a background image
//UIImage *backgroundImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"movies" ofType:#"jpg"]];
//UIImageView *backgroundView = [[UIImageView alloc] initWithImage:backgroundImage];
//adjust the frame for the case of navigation or tabbars
//backgroundView.frame = CGRectMake(0, 0, 320, 460);
//add background view and send it to the back
//[self.viewController.view addSubview:backgroundView];
//[self.viewController.view sendSubviewToBack:backgroundView];
//[backgroundView release];
//UIImage *img1= [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://122.183.217.134:8080/sivajitv/photos/20101216001017.jpg"]]];
//NSLog(#"ERROR1:%#",img1);
//NSData *imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:#"http://122.183.217.134:8080/sivajitv/photos/20101216001017.jpg"]];
//NSLog(#"ERROR12:%#",imageData);
}
There are so many things wrong with your code it is hard to know where to begin:
client.connect; is syntactic sugar for [client connect], however since connect is not a property (at least I hope it is not a property), you should not use the dot-notation.
The argument to isEqualToString: expects an NSString * object, not NSNull *. If you want to see whether the variable points to a string (as opposed to nil), or, if you want to make sure that the string actually contains characters, use:
if ([main_str length])
// do something
You assign a new mutable array that you own to id_arr using id_arr=[[NSMutableArray alloc]init];, however you completely overwrite this reference later with id_arr=[[udf objectForKey:#"id_value"] componentsSeparatedByString:#","];. This means that the original array that you created (and own) can no longer be referenced, and is leaked.
You never initialise the object that you allocated:
js=[[JsontoObject alloc]sivajiTV_response:main_str];
You create an Event object, but never use it or release it (this is a memory leak):
e1=[[Event alloc]init];

NSScrollView gives error when scrolling "-[CALayer isEqual:]: message sent to deallocated instance"

I'm trying to fix my code but I have no idea why I'm getting these errors:
modifying layer that is being finalized - 0x11818240
2010-09-10 02:35:53.022 iPhone Monkey Curling[1606:207] modifying layer that is being finalized - 0x11818240
2010-09-10 02:35:53.023 iPhone Monkey Curling[1606:207] modifying layer that is being finalized - 0x11818240
2010-09-10 02:35:54.671 iPhone Monkey Curling[1606:207] *** -[CALayer isEqual:]: message sent to deallocated instance 0x11818240
This happens when my all_score_table scroll view has had an attempt to scroll it (Crashes immediately on scroll attempt). Here is my code which sets the scroll views:
NSMutableArray * scores_data = [[first_data componentsSeparatedByString: #"\n"] mutableCopy];
if ([scores_data count] != 3) {
UIAlertView *connection_alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Malformed server response." delegate:nil cancelButtonTitle:#"Close" otherButtonTitles: nil];
[connection_alert show];
[connection_alert release];
return;
}
if([[scores_data objectAtIndex:0] isEqual:#""]){
[scores_data replaceObjectAtIndex:0 withObject:#"No scores for today,"];
}
if([[scores_data objectAtIndex:1] isEqual:#""]){
[scores_data replaceObjectAtIndex:1 withObject:#"No scores this week,"];
}
if([[scores_data objectAtIndex:2] isEqual:#""]){
[scores_data replaceObjectAtIndex:2 withObject:#"No scores,"];
}
[scores_data replaceObjectAtIndex:0 withObject: [[scores_data objectAtIndex:0] componentsSeparatedByString: #";"]];
[scores_data replaceObjectAtIndex:1 withObject: [[scores_data objectAtIndex:1] componentsSeparatedByString: #";"]];
[scores_data replaceObjectAtIndex:2 withObject: [[scores_data objectAtIndex:2] componentsSeparatedByString: #";"]];
NSLog(#"scores_data");
if (todays_scores_table){
//One of the tables exist so all of them must. Release them for renewal.
[todays_scores_table release];
[week_scores_table release];
[all_scores_table release];
[online_scores_pages release]; //release pages also
}
NSLog(#"1");
todays_scores_table = [[UIScrollView alloc] initWithFrame:CGRectMake(10, 110, 295, 300)];
week_scores_table = [[UIScrollView alloc] initWithFrame:CGRectMake(330, 110, 295, 300)];
all_scores_table = [[UIScrollView alloc] initWithFrame:CGRectMake(650, 110, 295, 300)];
todays_scores_table.contentSize = CGSizeMake(205, 60 + 40*[[scores_data objectAtIndex:0] count]);
week_scores_table.contentSize = CGSizeMake(205, 60 + 40*[[scores_data objectAtIndex:1] count]);
all_scores_table.contentSize = CGSizeMake(205, 60 + 40*[[scores_data objectAtIndex:2] count]);
NSLog(#"2");
NSArray * score_data;
NSString * path = [[NSBundle mainBundle] pathForResource: #"single_score_image" ofType:#"png"];
NSData * data = [[NSData alloc] initWithContentsOfFile:path];
UIImage * background_image = [[UIImage alloc] initWithData:data];
UIImageView * background_view;
UIImage * header_image;
if(submission){
path = [[NSBundle mainBundle] pathForResource: #"scores_header" ofType:#"png"];
[data release];
NSLog(#"3");
data = [[NSData alloc] initWithContentsOfFile:path];
header_image = [[UIImage alloc] initWithData:data];
}
UIImageView * header_view;
int offset;
UILabel * label;
NSLog(#"4");
UIScrollView * tables[3] = {todays_scores_table,week_scores_table,all_scores_table};
online_scores_pages = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 420)];
online_scores_pages.contentSize = CGSizeMake(960, 420);
online_scores_pages.pagingEnabled = YES; //Act like iphone home page
UIImage * title_image;
UIImageView * title_view;
NSLog(#"5");
//border for scores table
[data release];
path = [[NSBundle mainBundle] pathForResource: #"score_table_border" ofType:#"png"];
data = [[NSData alloc] initWithContentsOfFile:path];
UIImage * border_image = [[[UIImage alloc] initWithData:data] autorelease];
UIImageView * score_table_border;
for (int a = 0; a < 3; a++) {
if(submission){ //Only do header when submitting score
header_view = [[UIImageView alloc] initWithImage: header_image];
header_view.frame = CGRectMake(10, 10, 275, 30);
NSLog(#"5A");
[tables[a] addSubview: header_view];
[header_view release];
label = [[UILabel alloc] initWithFrame:CGRectMake(25, 10, 245, 30)];
label.backgroundColor = [UIColor clearColor];
NSLog(#"5B");
NSString * end;
NSLog(#"5C");
if ([[scores_data objectAtIndex:a+3] characterAtIndex:0] == '1'){
end = #"st";
}else if ([[scores_data objectAtIndex:a+3] characterAtIndex:0] == '2'){
end = #"nd";
}else if ([[scores_data objectAtIndex:a+3] characterAtIndex:0] == '3'){
end = #"rd";
}else{
end = #"th";
}
NSArray * pos_data = [[scores_data objectAtIndex:a+3] componentsSeparatedByString: #"/"];
label.text = [NSString stringWithFormat: #"You came %#%# from %# scores.",[pos_data objectAtIndex:0],end,[pos_data objectAtIndex:1]];
[tables[a] addSubview:label];
NSLog(#"5E");
[label release];
NSLog(#"6");
}
for (int x = 0; x < [[scores_data objectAtIndex:a] count]; x++){
score_data = [[[scores_data objectAtIndex:a] objectAtIndex:x] componentsSeparatedByString: #","];
//Image for each score
offset = 50 + 40*x;
background_view = [[UIImageView alloc] initWithImage: background_image];
background_view.frame = CGRectMake(10, offset, 275, 30); //Reposition
[tables[a] addSubview: background_view];
[background_view release];
//Add score position
label = [[UILabel alloc] initWithFrame:CGRectMake(10, offset, 30, 30)];
label.backgroundColor = [UIColor clearColor];
label.text = [NSString stringWithFormat: #"%i",x+1];
label.textAlignment = UITextAlignmentCenter;
[tables[a] addSubview:label];
[label release];
NSLog(#"7 %# \n\n %#",score_data,scores_data);
//Add name
label = [[UILabel alloc] initWithFrame:CGRectMake(55, offset, 190, 30)];
label.backgroundColor = [UIColor clearColor];
label.text = [score_data objectAtIndex:0];
[tables[a] addSubview:label];
[label release];
//Add score
label = [[UILabel alloc] initWithFrame:CGRectMake(55, offset, 225, 30)];
label.backgroundColor = [UIColor clearColor];
label.text = [NSString stringWithFormat: #"%#",[score_data objectAtIndex:1]];
label.textAlignment = UITextAlignmentRight;
[tables[a] addSubview:label];
[label release];
NSLog(#"8");
}
//Add title
switch (a) {
case 0:
path = [[NSBundle mainBundle] pathForResource: #"todays_scores_title" ofType:#"png"];
break;
case 1:
path = [[NSBundle mainBundle] pathForResource: #"week_scores_title" ofType:#"png"];
break;
case 2:
path = [[NSBundle mainBundle] pathForResource: #"all_scores_title" ofType:#"png"];
break;
}
[data release];
data = [[NSData alloc] initWithContentsOfFile:path];
title_image = [[[UIImage alloc] initWithData:data] autorelease];
title_view = [[[UIImageView alloc] initWithImage: title_image] autorelease];
title_view.frame = CGRectMake(25 + 320*a, 15, 270, 75); //Reposition and resize
[online_scores_pages addSubview:title_view];
NSLog(#"9");
//Add table
score_table_border = [[UIImageView alloc] initWithImage: border_image];
score_table_border.frame = CGRectMake(320*a, 100, 320, 320); //Reposition
[online_scores_pages addSubview: tables[a]];
[online_scores_pages addSubview: score_table_border];
[score_table_border release];
}
[data release];
if(submission){
[header_image release];
[header_view release];
}
[background_image release];
[background_view release];
[self addSubview: online_scores_pages];
[online_scores_pages becomeFirstResponder];
Thank you for any help. It is much appreciated.
The only iEqual: that I see is in the series of tests:
if([[scores_data objectAtIndex:0] isEqual:#""]){
if([[scores_data objectAtIndex:1] isEqual:#""]){
if([[scores_data objectAtIndex:2] isEqual:#""]){
So looking back at scores_data I see:
MutableArray * scores_data = [[first_data componentsSeparatedByString: #"\n"] mutableCopy];
Is first_data a NSString? If so I'm suspecting that componentsSeparatedByString will return a array of strings. This means that when you do [scores_data objectAtIndex:?] you will get a string.
The isEqual: at this point then looks wrong. Instead of isEqual: you should probably use isEqualToString:.
However, you're seeing a problem with accessing a deallocated object. That implies an excessive number of releases and I can't see that here.
I don't like that call to "mutableCopy" that you are using. I'd prefer to be more explicit in the initialisation:
MutableArray * scores_data = [[NSMutableArray alloc] initWithArray:[first_data componentsSeparatedByString: #"\n"]];
Finally! I found the problem.
I had this call - [background_view release]; once to many. I remove it at the end as it was being released when necessary in the for loop.
Now it works!!!!