gpt4 book ai didi

iphone - 显示 Plist 词典中的随机单词 - 内存泄漏?

转载 作者:行者123 更新时间:2023-12-03 17:37:02 25 4
gpt4 key购买 nike

我是 iPhone 开发新手。我是“守旧派” - 我在编程时被迫使用过程等。现在一切都是面向对象的,但我的风格仍然一如既往。请记住这一点。我的项目很小,实际上只是一个概念证明。

下面的程序在计时器上运行 - 每 30 秒它就会从我的应用程序存储在 Dictionary.plist 中的姓名数据库列表中随机读取一个婴儿名字。然后它会在 iPhone 屏幕上显示该名称。

您可以查看下面代码的完整相关部分。发生的情况是 - 如果我增加计时器以非常快地运行它 - 最终它似乎会耗尽内存或像它刚刚显示的那样???而不是下一个随机的婴儿名字。我怀疑这是因为我每次读取数据库文件时都没有关闭它。

无论如何,有人可以看看我的代码(考虑到我的上述评论)并告诉我需要添加什么来阻止它显示???经过这么多次运行..

我每次只在 ShowNextName 中打开文件,因为我无法找到其他方法来做到这一点..

我知道在这段代码的开头使用全局变量等并不是很好的风格,但是是否有一种方法可以重组或添加一些东西来阻止它“崩溃”或在运行了这么多次之后变得有点有趣。 ..

我很感激。谢谢。

#import "BabyNameViewController.h"

@implementation BabyNameViewController


NSDictionary *dictionary;
NSString *name;

int nameCount = 0;
int RecordIndex = 0;


- (void)ShowNextname;
{
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:@"Dictionary.plist"];
NSArray* plistArray = [NSArray arrayWithContentsOfFile:finalPath];

// Generate a random number between 0 and (the number of records-1) - used as a random index!

RecordIndex=arc4random()%[plistArray count];


// Select and display currently selected record from the array.
dictionary = [plistArray objectAtIndex:RecordIndex];
name = [dictionary objectForKey:@"name"];

[nameLabelOutlet setText: [NSString stringWithFormat: @"Random Baby Name is: %@", name]];

}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];

// Initial App entry point - startup code..


// Open the dictionary to count the number of names and store it for later use.
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:@"Dictionary.plist"];
NSArray* plistArray = [NSArray arrayWithContentsOfFile:finalPath];
nameCount = [plistArray count];

// Generate random name from database
[self ShowNextname];

// Start up the nameUpdate timer.
[NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(nameUpdate) userInfo:nil repeats:YES];

}

-(void) nameUpdate {
[self ShowNextname];
}

最佳答案

问题可能是每 30 秒您就会将 plist 重新加载到新数组中。您应该做的是在 viewDidLoad 中将 plist 加载到对象(您的 View Controller 类)中的实例变量中,然后在 showNextName 中使用该实例变量。 (另外,我总是以小写字母开头命名方法,以大写字母开头命名类,否则人们可能会认为 ShowNextname 是一个类而不是方法。)

另外,不要忘记在 dealloc 方法中添加 [plistArray release];

这里有一个很好的免费文档,您可能想阅读,它可能会对某些人有所帮助:

http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/OOP_ObjC/Introduction/Introduction.html

关于iphone - 显示 Plist 词典中的随机单词 - 内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2075592/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com