Многократное распределение времени и выпуска - PullRequest
0 голосов
/ 18 августа 2011

Я создаю приложение для викторины для iPhone / iPad (универсальное приложение). На симуляторе оно работает нормально, но на реальном устройстве я столкнулся с некоторой проблемой.и UIButtons программно, и я использую их так много раз для отображения вопросов и ответов один за другим.

Проблема в том, что когда я доходил до вопросов с 20 по 22, происходит сбой приложения.Я не знаю почему.я не обнаружил утечки памяти.Я освобождаю все метки и кнопки в функции -dealloc.
возможно, это происходит потому, что 22 вопроса занимают немного памяти и не освобождаются до вызова функции dealloc.

Что я хочу, есть ли способ освободить ярлыки и кнопки после каждого вопроса, а затем он будет распределяться снова?или любым способом, которым я могу использовать меньше памяти для выделения меток и кнопок ??

Я использую этот код:

//lbl ref to btn1
ans1 = [[[UILabel alloc] initWithFrame:CGRectMake(36, 292, 697, 100)] autorelease];
ans1.numberOfLines = 0;
ans1.font = [UIFont systemFontOfSize:26];
ans1.text = [theQuiz objectAtIndex:row+1];
ans1.lineBreakMode = UILineBreakModeWordWrap;
[ans1 sizeToFit];
//[self.view addSubview:ans1];
//lbl ref to btn2
ans2 = [[[UILabel alloc] initWithFrame:CGRectMake(36, 312 + ans1.frame.size.height , 697, 100)] autorelease];
ans2.numberOfLines = 0;
ans2.font = [UIFont systemFontOfSize:26];
ans2.text = [theQuiz objectAtIndex:row+2];
ans2.lineBreakMode = UILineBreakModeWordWrap;
[ans2 sizeToFit];
// [self.view addSubview:ans2];
//lbl ref to btn3
ans3 = [[[UILabel alloc] initWithFrame:CGRectMake(36 ,332 + ans1.frame.size.height + ans2.frame.size.height , 697 , 100)] autorelease];
ans3.numberOfLines = 0;
ans3.font = [UIFont systemFontOfSize:26];
ans3.text = [theQuiz objectAtIndex:row+3] ;
ans3.lineBreakMode = UILineBreakModeWordWrap;
[ans3 sizeToFit];
// [self.view addSubview:ans3];
//lbl ref to btn4
ans4 = [[[UILabel alloc] initWithFrame:CGRectMake(36, 352 + ans1.frame.size.height + ans2.frame.size.height + ans3.frame.size.height, 697, 100)] autorelease];
ans4.numberOfLines = 0;
ans4.font = [UIFont systemFontOfSize:26];
ans4.text = [theQuiz objectAtIndex:row+4];
ans4.lineBreakMode = UILineBreakModeWordWrap;
[ans4 sizeToFit];
// [self.view addSubview:ans4];

rightAnswer = [[theQuiz objectAtIndex:row+5] intValue];

Question = [[[UILabel alloc] initWithFrame:CGRectMake(22, 130, 725, 160)] autorelease];
Question.numberOfLines = 0;
//Question.font = [UIFont systemFontOfSize:27];
Question.text = [NSString stringWithFormat:@"%@" ,selected1];
Question.lineBreakMode = UILineBreakModeWordWrap;
[Question setFont:[UIFont fontWithName:@"Futura" size:26]];
Question.backgroundColor = [UIColor clearColor];
[Question sizeToFit];
[self.view addSubview:Question];

//For 1st Option.
button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self 
           action:@selector(buttonOne)
 forControlEvents:UIControlEventTouchDown];
button.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button.titleLabel.font = [UIFont systemFontOfSize:24];
[button setTitle:[theQuiz objectAtIndex:row+1] forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button.frame = CGRectMake(34, 200 + Question.frame.size.height , 700, ans1.frame.size.height + 20) ;
[self.view addSubview:button];
button.layer.borderWidth = 3;
button.layer.borderColor = [[UIColor purpleColor ] CGColor];
button.layer.cornerRadius = 10.0;
[button setBackgroundImage:[UIImage imageNamed:@"buttun.png"] forState:UIControlStateNormal];
button.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);

//For 2nd Option.
button2 = [UIButton buttonWithType:UIButtonTypeCustom];
[button2 addTarget:self 
            action:@selector(buttonTwo)
  forControlEvents:UIControlEventTouchDown];
[button2 setTitle:[theQuiz objectAtIndex:row+2] forState:UIControlStateNormal];
[button2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button2.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button2.titleLabel.font = [UIFont systemFontOfSize:24];
button2.frame = CGRectMake(34, 230 + Question.frame.size.height + button.frame.size.height , 700, ans2.frame.size.height + 20);
button2.layer.borderWidth = 3;
button2.layer.borderColor = [[UIColor darkGrayColor ] CGColor];
button2.layer.cornerRadius = 10.0;
[self.view addSubview:button2];
[button2 setBackgroundImage:[UIImage imageNamed:@"buttun2.png"] forState:UIControlStateNormal];
button2.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);

//For 3rd Option.
button3 = [UIButton buttonWithType:UIButtonTypeCustom];
[button3 addTarget:self 
            action:@selector(buttonThree)
  forControlEvents:UIControlEventTouchDown];
[button3 setTitle:[theQuiz objectAtIndex:row+3] forState:UIControlStateNormal];
[button3 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button3.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button3.titleLabel.font = [UIFont systemFontOfSize:24];
button3.frame = CGRectMake(34, 260 + Question.frame.size.height + button.frame.size.height + button2.frame.size.height , 700, ans3.frame.size.height + 20);
button3.layer.borderWidth = 3;
button3.layer.borderColor = [[UIColor purpleColor ] CGColor];
button3.layer.cornerRadius = 10.0;

[self.view addSubview:button3];
[button3 setBackgroundImage:[UIImage imageNamed:@"buttun.png"] forState:UIControlStateNormal];
button3.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);

//For 4th Option.
button4 = [UIButton buttonWithType:UIButtonTypeCustom];
[button4 addTarget:self 
            action:@selector(buttonFour)
  forControlEvents:UIControlEventTouchDown];
[button4 setTitle:[theQuiz objectAtIndex:row+4] forState:UIControlStateNormal];
[button4 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button4.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button4.titleLabel.font = [UIFont systemFontOfSize:24];
button4.frame = CGRectMake(34, 290 + Question.frame.size.height + button.frame.size.height + button2.frame.size.height + button3.frame.size.height , 700, ans4.frame.size.height + 20);
button4.layer.borderWidth = 3;
button4.layer.borderColor = [[UIColor darkGrayColor ] CGColor];
button4.layer.cornerRadius = 10.0;
[self.view addSubview:button4];
[button4 setBackgroundImage:[UIImage imageNamed:@"buttun2.png"] forState:UIControlStateNormal];
button4.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);

NSString *strright = [theQuiz objectAtIndex:row+7];
//NSString *strtext = [[NSString alloc] initWithFormat:@"%@" , strright];

rightans = [[[UILabel alloc] initWithFrame:CGRectMake(50, 330, 650, 150)]autorelease];
rightans.numberOfLines = 0;
rightans.text = [NSString stringWithFormat:@"%@" , strright];
rightans.backgroundColor = [UIColor clearColor];
rightans.font = [UIFont systemFontOfSize:26];
[self.view addSubview:rightans];
[rightans sizeToFit];
[rightans setHidden:YES];

//Description.
NSString *des = [theQuiz objectAtIndex:row+6];
//  NSString *destext = [[NSString alloc] initWithFormat:@"\n> Explanation :\n%@\n\n" , des];

Description = [[[UILabel alloc] initWithFrame:CGRectMake(40, 400 + rightans.frame.size.height , 690, 150)] autorelease];
Description.numberOfLines = 0;
// Description.font = [UIFont systemFontOfSize:13.5];
Description.text = [NSString stringWithFormat:@"\n> Explanation :\n%@\n\n" , des];
[Description setFont:[UIFont fontWithName:@"Futura" size:26]];
Description.lineBreakMode = UILineBreakModeWordWrap;
Description.backgroundColor = [UIColor clearColor];
[Description sizeToFit];
[self.view addSubview:Description];
[Description setHidden:YES];


ContainerView = [[UIView alloc] initWithFrame:CGRectMake(30, 400 + rightans.frame.size.height , 700 ,Description.frame.size.height)];
ContainerView.backgroundColor = [UIColor clearColor];
ContainerView.layer.cornerRadius = 10.0;
ContainerView.layer.borderColor = [[UIColor grayColor] CGColor];
ContainerView.layer.borderWidth = 3;
// [ContainerView addSubview:Description];
[self.view addSubview:ContainerView];
[ContainerView setHidden:YES];

Любая помощь ??
Спасибо.

Ответы [ 4 ]

2 голосов
/ 18 августа 2011
  1. Как только вы добавите метку как подпредставление к представлению - представление сохранит метку, которую вы можете выпустить, В вашем случае вы не выпускаете ContainerView
  2. Вы не должны выпускать автоматически выпущенные объекты - это нормально
2 голосов
/ 18 августа 2011

Вы не должны выпускать объекты автоматического выпуска.

1 голос
/ 18 августа 2011

Во-первых, вы должны освободить объект, как только добавите его в представление, используя [self.view addSubview: myObj]. Когда вы добавляете объект, подобный этому, его счетчик хранения увеличивается родительским представлением, и вы должны освободить его (чтобы уменьшить его счетчик хранения), чтобы разрешить его сборку мусора. Ваш код должен быть как-

[self.view addSubview: myObj];
[myObj release];

Во-вторых, у вас есть журнал сбоев?

НТН,

Акшай

0 голосов
/ 18 августа 2011

1) Простое правило: вы освобождаете все, что у вас выделено или сохранено, скопировано ... Все остальные ваши переменные будут автоматически освобождены.В вашем коде вы выделяете все метки, но не кнопки. Вы должны освободить все метки после добавления их в subView.Кнопки, которые вы просто добавляете в subView, а не отпускаете послесловия, поскольку вы не выделяете его .. Поскольку вы задаете вопрос similiar в течение 2 дней, я просто работал над вашим кодом

//lbl ref to btn1
ans1 = [[[UILabel alloc] initWithFrame:CGRectMake(36, 292, 697, 100)] autorelease];
ans1.numberOfLines = 0;
ans1.font = [UIFont systemFontOfSize:26];
ans1.text = [theQuiz objectAtIndex:row+1];
ans1.lineBreakMode = UILineBreakModeWordWrap;
[ans1 sizeToFit];
[self.view addSubview:ans1];


//lbl ref to btn2
ans2 = [[[UILabel alloc] initWithFrame:CGRectMake(36, 312 + ans1.frame.size.height , 697, 100)] autorelease];
ans2.numberOfLines = 0;
ans2.font = [UIFont systemFontOfSize:26];
ans2.text = [theQuiz objectAtIndex:row+2];
ans2.lineBreakMode = UILineBreakModeWordWrap;
[ans2 sizeToFit];
[self.view addSubview:ans2];


//lbl ref to btn3
ans3 = [[[UILabel alloc] initWithFrame:CGRectMake(36 ,332 + ans1.frame.size.height + ans2.frame.size.height , 697 , 100)] autorelease];
ans3.numberOfLines = 0;
ans3.font = [UIFont systemFontOfSize:26];
ans3.text = [theQuiz objectAtIndex:row+3] ;
ans3.lineBreakMode = UILineBreakModeWordWrap;
[ans3 sizeToFit];
[self.view addSubview:ans3];


//lbl ref to btn4
ans4 = [[[UILabel alloc] initWithFrame:CGRectMake(36, 352 + ans1.frame.size.height + ans2.frame.size.height + ans3.frame.size.height, 697, 100)] autorelease];
ans4.numberOfLines = 0;
ans4.font = [UIFont systemFontOfSize:26];
ans4.text = [theQuiz objectAtIndex:row+4];
ans4.lineBreakMode = UILineBreakModeWordWrap;
[ans4 sizeToFit];
[self.view addSubview:ans4];

rightAnswer = [[theQuiz objectAtIndex:row+5] intValue];

Question = [[[UILabel alloc] initWithFrame:CGRectMake(22, 130, 725, 160)] autorelease];
Question.numberOfLines = 0;
//Question.font = [UIFont systemFontOfSize:27];
Question.text = [NSString stringWithFormat:@"%@" ,selected1];
Question.lineBreakMode = UILineBreakModeWordWrap;
[Question setFont:[UIFont fontWithName:@"Futura" size:26]];
Question.backgroundColor = [UIColor clearColor];
[Question sizeToFit];
[self.view addSubview:Question];

//For 1st Option.
button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:@selector(buttonOne) forControlEvents:UIControlEventTouchDown];
button.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button.titleLabel.font = [UIFont systemFontOfSize:24];
[button setTitle:[theQuiz objectAtIndex:row+1] forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button.frame = CGRectMake(34, 200 + Question.frame.size.height , 700, ans1.frame.size.height + 20) ;
button.layer.borderWidth = 3;
button.layer.borderColor = [[UIColor purpleColor ] CGColor];
button.layer.cornerRadius = 10.0;
[button setBackgroundImage:[UIImage imageNamed:@"buttun.png"] forState:UIControlStateNormal];
button.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);
[self.view addSubview:button];



//For 2nd Option.
button2 = [UIButton buttonWithType:UIButtonTypeCustom];
[button2 addTarget:self action:@selector(buttonTwo) forControlEvents:UIControlEventTouchDown];
[button2 setTitle:[theQuiz objectAtIndex:row+2] forState:UIControlStateNormal];
[button2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button2.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button2.titleLabel.font = [UIFont systemFontOfSize:24];
button2.frame = CGRectMake(34, 230 + Question.frame.size.height + button.frame.size.height , 700, ans2.frame.size.height + 20);
button2.layer.borderWidth = 3;
button2.layer.borderColor = [[UIColor darkGrayColor ] CGColor];
button2.layer.cornerRadius = 10.0;
[button2 setBackgroundImage:[UIImage imageNamed:@"buttun2.png"] forState:UIControlStateNormal];
button2.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);
[self.view addSubview:button2];


//For 3rd Option.
button3 = [UIButton buttonWithType:UIButtonTypeCustom];
[button3 addTarget:self action:@selector(buttonThree) forControlEvents:UIControlEventTouchDown];
[button3 setTitle:[theQuiz objectAtIndex:row+3] forState:UIControlStateNormal];
[button3 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button3.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button3.titleLabel.font = [UIFont systemFontOfSize:24];
button3.frame = CGRectMake(34, 260 + Question.frame.size.height + button.frame.size.height + button2.frame.size.height , 700, ans3.frame.size.height + 20);
button3.layer.borderWidth = 3;
button3.layer.borderColor = [[UIColor purpleColor ] CGColor];
button3.layer.cornerRadius = 10.0;
[button3 setBackgroundImage:[UIImage imageNamed:@"buttun.png"] forState:UIControlStateNormal];
button3.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);
[self.view addSubview:button3];



//For 4th Option.
button4 = [UIButton buttonWithType:UIButtonTypeCustom];
[button4 addTarget:self action:@selector(buttonFour) forControlEvents:UIControlEventTouchDown];
[button4 setTitle:[theQuiz objectAtIndex:row+4] forState:UIControlStateNormal];
[button4 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button4.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button4.titleLabel.font = [UIFont systemFontOfSize:24];
button4.frame = CGRectMake(34, 290 + Question.frame.size.height + button.frame.size.height + button2.frame.size.height + button3.frame.size.height , 700, ans4.frame.size.height + 20);
button4.layer.borderWidth = 3;
button4.layer.borderColor = [[UIColor darkGrayColor ] CGColor];
button4.layer.cornerRadius = 10.0;
[button4 setBackgroundImage:[UIImage imageNamed:@"buttun2.png"] forState:UIControlStateNormal];
button4.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);
[self.view addSubview:button4];



NSString *strright = [theQuiz objectAtIndex:row+7];
//NSString *strtext = [[NSString alloc] initWithFormat:@"%@" , strright];



rightans = [[[UILabel alloc] initWithFrame:CGRectMake(50, 330, 650, 150)]autorelease];
rightans.numberOfLines = 0;
rightans.text = [NSString stringWithFormat:@"%@" , strright];
rightans.backgroundColor = [UIColor clearColor];
rightans.font = [UIFont systemFontOfSize:26];
[rightans sizeToFit];
[rightans setHidden:YES];
[self.view addSubview:rightans];


//Description.
NSString *des = [theQuiz objectAtIndex:row+6];
//  NSString *destext = [[NSString alloc] initWithFormat:@"\n> Explanation :\n%@\n\n" , des];


Description = [[[UILabel alloc] initWithFrame:CGRectMake(40, 400 + rightans.frame.size.height , 690, 150)] autorelease];
Description.numberOfLines = 0;
// Description.font = [UIFont systemFontOfSize:13.5];
Description.text = [NSString stringWithFormat:@"\n> Explanation :\n%@\n\n" , des];
[Description setFont:[UIFont fontWithName:@"Futura" size:26]];
Description.lineBreakMode = UILineBreakModeWordWrap;
Description.backgroundColor = [UIColor clearColor];
[Description sizeToFit];
[Description setHidden:YES];
[self.view addSubview:Description];



ContainerView = [[UIView alloc] initWithFrame:CGRectMake(30, 400 + rightans.frame.size.height , 700 ,Description.frame.size.height)];
ContainerView.backgroundColor = [UIColor clearColor];
ContainerView.layer.cornerRadius = 10.0;
ContainerView.layer.borderColor = [[UIColor grayColor] CGColor];
ContainerView.layer.borderWidth = 3;
// [ContainerView addSubview:Description];
[ContainerView setHidden:YES];
[self.view addSubview:ContainerView];
[ContainerView release];

Некоторые другиеПримечания.

1) Имя переменной всегда должно начинаться с маленькой буквы. Это не письменное правило, а хорошая практика, более удобная для вас и для других (таких как мы), просматривающих его.Неверные имена переменных, такие как «Описание» и «Вопрос».

2) Никогда не размещайте свой вопрос повторно. Если вы только лучше отформатировали код, вы должны получить ответ в самом предыдущем вопросе.

...