Iphone 创建UI按钮
在loadView期间,我创建了20个UIButton,我希望根据UIPageControl的状态更改其标题文本 我有一个预保存plist,它加载到一个名为arrChars的NSArray中。在当前页面发生更改时,我将按钮标题设置为数组中的相关文本标题。执行此操作的代码是:Iphone 创建UI按钮,iphone,ios,memory-management,uibutton,Iphone,Ios,Memory Management,Uibutton,在loadView期间,我创建了20个UIButton,我希望根据UIPageControl的状态更改其标题文本 我有一个预保存plist,它加载到一个名为arrChars的NSArray中。在当前页面发生更改时,我将按钮标题设置为数组中的相关文本标题。执行此操作的代码是: for (int i = 1; i < (ButtonsPerPage + 1); i++) { UIButton *uButton = (UIButton *)[self.view viewWithTag:
for (int i = 1; i < (ButtonsPerPage + 1); i++) {
UIButton *uButton = (UIButton *)[self.view viewWithTag:i];
if(iPage == 1) {
iArrPos = (i - 1);
} else {
iArrPos = (iPage * ButtonsPerPage) + (i - 1);
}
[uButton setAlpha:0];
NSLog(@"Trying: %d of %d", iArrPos, [self.arrChars count]);
if (iArrPos >= [self.arrChars count]) {
[uButton setTitle: @"" forState: UIControlStateNormal];
} else {
NSString *value = [[NSString alloc] initWithFormat:@"%@", [self.arrChars objectAtIndex:iArrPos]];
NSLog(@"%@", value);
[uButton setTitle: [[NSString stringWithFormat:@"%@", value] forState: UIControlStateNormal];
[value release];
//////Have tried:
//////[uButton setTitle: value forState: UIControlStateNormal];
//////Have also tried:
//////[uButton setTitle: [self.arrChars objectAtIndex:iArrPos] forState: UIControlStateNormal];
//////Have also also tried:
//////[uButton setTitle: [[self.arrChars objectAtIndex:iArrPos] autorelease] forState: UIControlStateNormal];
}
[uButton setAlpha:1];
}
当设置按钮的标题时,它似乎不会自动恢复上一个标题,分配会不断增加。我做错了什么
以前有人告诉我,通过分配来跟踪东西是追踪泄漏的一种不好的方式,因为据我所知,物体没有在仪器中泄漏,但我的总生存分配继续攀升,直到我得到一个内存警告。如果有更好的方法跟踪那里,我很想知道
更新
忘了提到,我没有使用从数组中检索到的值,而是将标题设置为@Test-这很好,而且每次我更改页面时不会出现无止境的增加。您正在进行大量不必要的字符串创建和格式设置。您可以替换这些行:
NSString *value = [[NSString alloc] initWithFormat:@"%@", [self.arrChars objectAtIndex:iArrPos]];
NSLog(@"%@", value);
[uButton setTitle: [[NSString stringWithFormat:@"%@", value] forState: UIControlStateNormal];
有了这些:
NSString *title = [self.arrChars objectAtIndex:iArrPos];
[uButton setTitle:title forState:UIControlStateNormal];
[title release];
使用setTitle:on title会增加保留计数-请务必在之后释放它。经过许多漫长的夜晚,我决定咬紧牙关,将此文件发送到苹果的DTS中 虽然答复是有用的,但并不是我所希望的。在arrChar中偶尔会出现一些标志符号,当加载时,我被告知不要卸载。详细说明: 据我所知,iOS不会在字形加载到内存后卸载它们。这就是为什么在Instrument.app中,当加载新字符时,内存分配会增加,而当以后来回时,内存分配会保持不变。我们几乎无法改变iOS的设计行为。如果您确实想要控制内存使用,您可以交替地将字符设置为图像,并使用UIImage imageWithContentsOfFile:来加载和释放
希望这对其他人有所帮助。谢谢。我最近才补充说,因为我认为这会让我有能力自己释放内存,而不是依靠自动释放。关于stringValue添加,这正在破坏我的代码“-[\uu NSCFString stringValue]:发送到实例0x1c13d0的无法识别的选择器”-这是否意味着我的plist没有正确设置为字符串?我将该部分改回stringWithFormat。self.arrChars中存储了什么类型的对象?数组的加载方式如下:self.arrChars=[[NSArray alloc]initWithContentsOfFile:[[NSBundle mainBundle]bundlePath]stringByAppendingString:@/chars.plist]];并包含一些特殊字符的组合。结构是:123……等等……好吧,我想我找到问题了。见上文。