Can I re-coding loop UIImageView to get shorter code? - iphone

Can I make this code shorter than this ?
- (void) setupFeature
{ NSArray *numbers = [NSArray arrayWithObjects: #"01", #"02", #"03",#"04",#"05",#"06", nil];
position = CGRectMake(7, position.origin.y+20, 72, 72);
int j=0;
NSString *pic;
UIImageView *a_pic;
NSMutableArray *C_Pic = [[[NSMutableArray alloc] init] autorelease];
for (int i=0; i<[numbers count]; i++)
{
UIImageView *picture = [[UIImageView alloc] init];
[C_Pic addObject:picture];
[picture release];
a_pic = [C_Pic objectAtIndex:i];
pic = [NSString stringWithFormat:#"iconD%#",[numbers objectAtIndex:i]];
a_pic.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:pic ofType:#"png"]];
if(j<4)
{
a_pic.frame = position;
[scrollView addSubview:a_pic];
position = CGRectMake(position.origin.x+77, position.origin.y, 72, 72);
j++;
}
else
{
j=0;
position = CGRectMake(7, position.origin.y+77, 72, 72);
NSLog(#"Pic%i position %#",i, NSStringFromCGRect(self.position));
a_pic.frame = position;
[scrollView addSubview:a_pic];
position = CGRectMake(position.origin.x+77, position.origin.y, 72, 72);
}
}
}
If it can be shorter ?? please , help me how to do that ?

Yes it can be shorter see this
- (void) setupFeature
{
NSArray *numbers = [NSArray arrayWithObjects: #"01", #"02", #"03",#"04",#"05",#"06", nil];
position = CGRectMake(7, position.origin.y+20, 72, 72);
int j=0;
NSString *pic;
UIImageView *a_pic;
NSMutableArray *C_Pic = [[[NSMutableArray alloc] init] autorelease];
for (int i=0; i<[numbers count]; i++)
{
UIImageView *picture = [[UIImageView alloc] init];
[C_Pic addObject:picture];
[picture release];
a_pic = [C_Pic objectAtIndex:i];
pic = [NSString stringWithFormat:#"iconD%#",[numbers objectAtIndex:i]];
a_pic.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:pic ofType:#"png"]];
if(j<4)
{
j++;
}
else
{
j=0;
position = CGRectMake(7, position.origin.y+77, 72, 72);
NSLog(#"Pic%i position %#",i, NSStringFromCGRect(self.position));
}
//No need to repeat this code
a_pic.frame = position;
[scrollView addSubview:a_pic];
position = CGRectMake(position.origin.x+77, position.origin.y, 72, 72);
}
}

Related

UIScrollView has White Space above SubViews

I am running across a weird issue, which I can't seem to figure out.
Upon adding multiple SubViews to a ScrollView, the ScrollViews keeps on adding a White Space ontop of the regular image
A bit better with more colors:
This is how it should look like:
The Image is perfectly scrollable.
This is the code I'm using to create the scrollview:
-(void)addImagesToScrollView
{
if (self.product != nil)
{
int imageCount = 0;
if (self.product.labelImage != nil)
{
UIImageView *labelImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height)];
labelImage.image = [UIImage imageWithData:self.product.labelImage];
labelImage.contentMode = UIViewContentModeScaleAspectFit;
labelImage.tag = 100;
[self.scrollView addSubview:labelImage];
imageCount += 1;
}
if (self.product.bottleImage != nil)
{
UIImageView *bottleImage = [[UIImageView alloc] initWithFrame:CGRectMake(self.scrollView.frame.size.width, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height)];
bottleImage.image = [UIImage imageWithData:self.product.bottleImage];
bottleImage.contentMode = UIViewContentModeScaleAspectFit;
bottleImage.tag = 101;
imageCount += 1;
[self.scrollView addSubview:bottleImage];
}
if (self.product.pourImage != nil)
{
UIImageView *pourImage = [[UIImageView alloc] initWithFrame:CGRectMake(self.scrollView.frame.size.width * 2, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height)];
pourImage.image = [UIImage imageWithData:self.product.pourImage];
pourImage.contentMode = UIViewContentModeScaleAspectFit;
pourImage.tag = 102;
imageCount += 1;
[self.scrollView addSubview:pourImage];
}
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * imageCount, self.scrollView.frame.size.height);
[self.scrollView setContentOffset:CGPointZero animated:NO];
}
}
Edit:
With a BackgroundColor:
use:
bottleImage.layer.color = [UIcolor blueColor].CGColor;
bottleImage.layer.borderWidth = 2.0f;
It will let you see the frame of your UIImageView maybe you are calculating incorrectly the frame
Use below code and you will get desired output. In the following code you app will use album photos and automatically sets size of the scrolling as per the number of images in album. And please modify according to your image repository.
-(void)getAllPictures
{
imageArray=[[NSArray alloc] init];
mutableArray =[[NSMutableArray alloc]init];
NSMutableArray* assetURLDictionaries = [[NSMutableArray alloc] init];
library = [[ALAssetsLibrary alloc] init];
void (^assetEnumerator)( ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop) {
if(result != nil) {
if([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto]) {
[assetURLDictionaries addObject:[result valueForProperty:ALAssetPropertyURLs]];
NSURL *url= (NSURL*) [[result defaultRepresentation]url];
[library assetForURL:url
resultBlock:^(ALAsset *asset) {
[mutableArray addObject:[UIImage imageWithCGImage:[[asset defaultRepresentation] fullScreenImage]]];
if ([mutableArray count]==count)
{
imageArray=[[NSArray alloc] initWithArray:mutableArray];
[self allPhotosCollected:imageArray];
}
}
failureBlock:^(NSError *error){ NSLog(#"operation was not successfull!"); } ];
}
}
};
NSMutableArray *assetGroups = [[NSMutableArray alloc] init];
void (^ assetGroupEnumerator) ( ALAssetsGroup *, BOOL *)= ^(ALAssetsGroup *group, BOOL *stop) {
if(group != nil) {
[group enumerateAssetsUsingBlock:assetEnumerator];
[assetGroups addObject:group];
count=[group numberOfAssets];
}
};
assetGroups = [[NSMutableArray alloc] init];
[library enumerateGroupsWithTypes:ALAssetsGroupAll
usingBlock:assetGroupEnumerator
failureBlock:^(NSError *error) {NSLog(#"There is an error");}];
}
-(void)allPhotosCollected:(NSArray*)imgArray
{
CGSize imageSize;
imageSize.width= imageView.bounds.size.width;
imageSize.height = imageView.bounds.size.height;
self.scrollView=[[UIScrollView alloc]init];
self.scrollView.frame = imageView.frame;
self.scrollView.contentSize = CGSizeMake(imageSize.width * imgArray.count, imageSize.height);
self.scrollView.pagingEnabled = YES;
self.scrollView.bounces=YES;
self.scrollView.scrollEnabled = YES;
self.scrollView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin;
[self.scrollView flashScrollIndicators];
[self.view addSubview:self.scrollView];
CGFloat xPos = 0.0;
for (UIImage *image in imgArray) {
imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(xPos, 0.0, imageSize.width, imageSize.height);
[self.scrollView addSubview:imageView];
xPos += imageSize.width;
// assuming ARC, otherwise release imageView
}
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 20,320 , 420)];
[self getAllPictures];
}

How to Access Particular view of a pageControl viewController?

Hi I m creating a project where multiple Images Loading from Server With some like Count and Comment Count and a Button to like the image. I m showing the individual Images With using a Slider Controller like PageControl.
this is My code for Showing the View
-(UIView*)reloadView:(DPSliderView *)sliderView viewAtIndex:(NSUInteger)idx
{
_loading_view.hidden=TRUE;
if (idx < [photos count]) {
NSDictionary *item = [photos objectAtIndex:idx];
PhotoView *v = [[PhotoView alloc] init];
v.photoIndex = idx;
v.imageView.imageURL = [DPAPI urlForPhoto:item[#"photo_220x220"]];
NSString *placename1 = [item valueForKeyPath:#"spotting.item.name"];
NSString *firstCapChar1 = [[placename1 substringToIndex:1] capitalizedString];
NSString *cappedString1 = [placename1 stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:firstCapChar1];
v.spotNameLabel.text = cappedString1;
NSString *placename = [item valueForKeyPath:#"spotting.place.name"];
NSString *firstCapChar = [[placename substringToIndex:1] capitalizedString];
NSString *cappedString = [placename stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:firstCapChar];
NSString *place1=[NSString stringWithFormat:#"%#",cappedString];
NSString *address=[NSString stringWithFormat:#"%#",[item valueForKeyPath:#"spotting.place.address"]];
NSString *location_str3 = [NSString stringWithFormat:#"# %#, %#",place1,address];
int cap_len=[place1 length];
int address_lenth=[address length];
ZMutableAttributedString *str = [[ZMutableAttributedString alloc] initWithString:location_str3
attributes:[NSDictionary dictionaryWithObjectsAndKeys:
[[FontManager sharedManager] zFontWithName:#"Lucida Grande" pointSize:12],
ZFontAttributeName,
nil]];
[str addAttribute:ZFontAttributeName value:[[FontManager sharedManager] zFontWithName:#"Lucida Grande" pointSize:12] range:NSMakeRange(0, cap_len+3)];
[str addAttribute:ZForegroundColorAttributeName value:[UIColor colorWithRed:241/255.0f green:73.0/255.0f blue:2.0/255.0f alpha:1.0]range:NSMakeRange(0, cap_len+3)];
[str addAttribute:ZForegroundColorAttributeName value:[UIColor colorWithRed:128.0/255.0f green:121.0/255.0f blue:98.0/255.0f alpha:1.0]range:NSMakeRange(cap_len+4, address_lenth)];
v.placefontlabel.zAttributedText=str;
v.likesCountLabel.text = [NSString stringWithFormat:#"%i", [item[#"likes_count"] intValue]];
if ([_device_lang_str isEqualToString:#"es"])
{
v.shightingsLabel.text = [NSString stringWithFormat:NSLocalizedString(#"%i Vistas", nil), [item[#"sightings_count"] intValue]];
}
else
{
v.shightingsLabel.text = [NSString stringWithFormat:NSLocalizedString(#"%i Sightings", nil), [item[#"sightings_count"] intValue]];
}
if ([nolocationstr isEqualToString:#"YES"])
{
v.distanceLabel.text =[NSString stringWithFormat:#"%.2f km", [item[#"distance"] floatValue]];
}
else
{
CLLocation *location1 = [[CLLocation alloc] initWithLatitude:[[item valueForKeyPath:#"spotting.place.lat"]floatValue] longitude:[[item valueForKeyPath:#"spotting.place.lng"] floatValue]];
CLLocation *location2 = [[CLLocation alloc] initWithLatitude:[_explore_lat_str floatValue] longitude:[_explore_lng_str floatValue]];
NSString *lat_laong=[NSString stringWithFormat:#"%f",[location1 distanceFromLocation:location2]];
int km=[lat_laong floatValue]*0.001;
NSString *distancestr=[NSString stringWithFormat:#"%d km",km];
float dist=[distancestr floatValue];
v.distanceLabel.text = [NSString stringWithFormat:#"%.2f km", dist];
}
if (![item[#"likes"] boolValue]) {
v.likeButton.enabled = YES;
v.likeButton.tag = idx;
[v.likeButton setImage:[UIImage imageNamed:#"like_new.png"] forState:UIControlStateNormal];
[v.likeButton addTarget:self action:#selector(likeAction:) forControlEvents:UIControlEventTouchUpInside];
}
else
{
v.likeButton.tag = idx;
[v.likeButton setImage:[UIImage imageNamed:#"like_new1.png"] forState:UIControlStateNormal];
}
NSArray *guides = item[#"guides"];
if ([guides count] > 0) {
NSString *guideType = [[guides objectAtIndex:0] valueForKey:#"type"];
UIImage *guidesIcon = [UIImage imageNamed:[NSString stringWithFormat:#"%#.png", guideType]];
v.guideButton.hidden = NO;
v.guideButton.tag = idx;
[v.guideButton setImage:guidesIcon forState:UIControlStateNormal];
[v.guideButton addTarget:self action:#selector(guideAction:) forControlEvents:UIControlEventTouchUpInside];
}
v.shareButton.tag = idx;
[v.shareButton addTarget:self action:#selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(photoTapGesture:)];
[v addGestureRecognizer:tapGesture];
[tapGesture release];
return [v autorelease];
} else {
UIImageView *iv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"sc_img.png"]];
UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
indicator.center = CGPointMake(CGRectGetMidX(iv.bounds), 110);
[indicator startAnimating];
[iv addSubview:indicator];
[indicator release];
return [iv autorelease];
}
}
Now My question is :
If i will Click on Like Button , Then i have to change the button image as well as like count. I can able to Change the Button Image By This Method
[sender setImage:[UIImage ImageNamed:#"image.png"]];
But How can I change the Like count of the Label ? How can i access the Particular label of the View ? I have assigned the tag But , I dont know how to assign it.I dont want to Reload Whole Slider as the Photo are loading from Network (Remote Server) . Thanks for your Time.
Just keep a reference to the label and update that.
// #interface
#property (nonatomic, strong) UILabel *myLabel;
// #implementation
_myLabel.text = #"Whatever.";
If you have multiple labels, set the tags when you create your views
newView.tag = sequenceNumber +100;
And then update
-(void)updateLabelWithTag:(NSInteger)tag {
UILabel *label = (UILabel*) [self.scrollView viewWithTag:tag];
label.text = #"Whatever.";
}

exc_bad_access when using a async request

Im making a async request but when I try to parse it with this code
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSDictionary *missionsDict = [responseString JSONValue];
/*NSArray *luckyNumbers = [json objectWithString:responseString error:&error];*/
NSLog(#"user Info array is: %#", missionsDict);
// NSDictionary *array = [luckyNumbers1 objectForKey:#"data"];
NSDictionary *missionsData;
missionsData = [missionsDict objectForKey:#"data"];
NSLog(#"missionsData is: %#", missionsData);
NSEnumerator *inner = [missionsData objectEnumerator];
UIScrollView *missionsScroll;
missionsScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
missionsScroll.contentSize = CGSizeMake(320, 1005);
[self.view addSubview:missionsScroll];
id value;
int badgeY1;
int badgeY2;
int badgeY3;
badgeY1 = 121;
badgeY2 = 161;
badgeY3 = 150;
while((value = [inner nextObject])) {
NSLog(#"progress is: %#", [value objectForKey:#"progress"]);
NSLog(#"user Info array is: %#", missionsDict);
NSLog(#"name is: %#",[value objectForKey:#"reward_definitions"]);
NSLog(#"missionsData is: %#", missionsData);
NSDictionary *moreData;
moreData = [value objectForKey:#"reward_definitions"];
NSEnumerator *inner = [moreData objectEnumerator];
id value2;
int badgeX;
badgeX = 10;
while((value2 = [inner nextObject])) {
UIProgressView *progressView;
progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, badgeY3, 372, 9)];
float progressValue;
progressValue = ([[[value objectForKey:#"progress"] objectForKey:#"earned"] floatValue] / [[[value objectForKey:#"progress"] objectForKey:#"possible"] floatValue]);
NSLog(#"progressValue is: %f", progressValue);
[progressView setProgress:progressValue];
[missionsScroll addSubview:progressView];
UILabel *missionName;
missionName = [[UILabel alloc] initWithFrame:CGRectMake(20, badgeY1, 280, 25)];
missionName.backgroundColor = [UIColor clearColor];
missionName.textColor = [UIColor whiteColor];
missionName.font = [UIFont fontWithName:#"Heiti TC" size:23.0];
missionName.text = [value objectForKey:#"name"];
[missionsScroll addSubview:missionName];
NSLog(#"badgeY2 is: %#", badgeY2);
badgesScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, badgeY2, 318, 70)];
badgesScroll.contentSize = CGSizeMake(320, 70);
[missionsScroll addSubview:badgesScroll];
NSLog(#"Image URL is: %#", [value2 objectForKey:#"image_url"]);
NSURL *url1 = [NSURL URLWithString: [NSString stringWithFormat:#"%#", [value2 objectForKey:#"image_url"]]];
NSData *urlData1 = [NSData dataWithContentsOfURL:url1];
UIImage *image1 = [UIImage imageWithData:urlData1];
UIImageView *badge = [[UIImageView alloc] initWithImage:image1];
[badge setFrame:CGRectMake(badgeX, -10, 70, 70)];
[badgesScroll addSubview:badge];
[badge release];
badgeCount = badgeCount+1;
badgeX = badgeX +80;
}
// NSLog(#"reward_definitions is: %#", [missionsData objectForKey:#"id"]);
// NSLog(#"Image URL is: %#", [[value objectForKey:#"reward_definitions"] objectForKey:#"image_url"]);
//if ( [array isKindOfClass:[NSDictionary class]] ) {
badgeY1 = badgeY1 +100;
badgeY2 = badgeY2 +100;
badgeY3 = badgeY3 +100;
missionCount = missionCount+1;
}
for (int b; badgeCount > 4; b = b+1) {
[badgesScroll setContentSize:CGSizeMake(badgesScroll.contentSize.width+80, badgesScroll.contentSize.height)];
}
for (int a; missionCount > 4; a = a+1) {
missionsScroll.contentSize = CGSizeMake(776, missionsScroll.contentSize.height+200);
}
}
It crashes because of EXC_BAD_ACCESS on NSLog(#"badgeY2 is: %#", badgeY2);
your badgeY2 contains an integer value. To print the integer value with NSLog, you must use %d
You should always keep it in mind while using NSLog, what kind of value it returns!
NSLog(#"badgeY2 is: %d", badgeY2);
There is another heck solution to just let you know
NSLog(#"%#", [NSNumber numberWithInt:badgeY2]);
These are the NSLog format specifiers :
%# Object
%d, %i signed int
%u unsigned int
%f float/double
%x, %X hexadecimal int
%o octal int
%zu size_t
%p pointer
Should be
NSLog(#"badgeY2 is: %i", badgeY2);
badgeY2 is an int, so you must use %i instead of %#

animationArray only playing last image

I currently have this method buttonHit that calls playAnimationToNumber which accepts an int, which is then in turn used to run through a loop playing an array of images for each iteration, however it only seems to be playing the last array.. can you see why? because I am slightly lost and would appreciate the help.
//attached to button and it calls animation method.
- (void)buttonHit:(id)sender{
[self playAnimationToNumber:5];
}
- (void)playAnimationToNumber:(int)number{
for (int counter=1; counter<=number; counter++) {
NSString *imageNameForFirstNumber = [NSString stringWithFormat:#"Flap%i.png", counter];
NSArray *imagesForAnimation = [NSArray arrayWithObjects:[UIImage imageNamed:#"FlapMoving1.png"], [UIImage imageNamed:#"FlapMoving2.png"], [UIImage imageNamed:imageNameForFirstNumber], nil];
animationArray.animationImages = [[NSArray alloc] initWithArray:imagesForAnimation];
animationArray.animationDuration = 0.5;
animationArray.animationRepeatCount = 1;
[animationArray startAnimating];
[self.view addSubview:animationArray];
}
[animationArray release];
}
WORKING CODE
'
- (void)playAnimationToNumber:(int)number{
NSMutableArray *imagesForAnimation = [[NSMutableArray alloc] initWithCapacity:0];
for (int counter=1; counter<=number; counter++) {
NSString *imageNameForFirstNumber = [NSString stringWithFormat:#"Flap%i.png", counter];
[imagesForAnimation addObject:[UIImage imageNamed:#"FlapMoving1.png"]];
[imagesForAnimation addObject:[UIImage imageNamed:#"FlapMoving2.png"]];
[imagesForAnimation addObject:[UIImage imageNamed:imageNameForFirstNumber]];
}
animationArray.animationImages = [NSArray arrayWithArray:imagesForAnimation];
animationArray.animationDuration = 5.9;
animationArray.animationRepeatCount = 1;
[animationArray startAnimating];
[self.view addSubview:animationArray];
[imagesForAnimation release];
}'
Here you go try this code.
- (void)playAnimationToNumber:(int)number{
NSMutableArray *imagesForAnimation = [[[NSMutable alloc] initWithCapacity:0] autoRelease];
[imagesForAnimation addObject:[UIImage imageNamed:#"FlapMoving1.png"]];
[imagesForAnimation addObject:[UIImage imageNamed:#"FlapMoving2.png"]];
for (int counter=1; counter<=number; counter++) {
NSString *imageNameForFirstNumber = [NSString stringWithFormat:#"Flap%i.png", counter];
[imagesForAnimation addObject:[UIImage imageNamed:imageNameForFirstNumber]];
}
animationArray.animationImages = [NSArray arrayWithArray:imagesForAnimation];
animationArray.animationDuration = 0.5;
animationArray.animationRepeatCount = 1;
[animationArray startAnimating];
[self.view addSubview:animationArray];
}
}

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!!!!