内存管理问题从字符串中检索特定的文本行

时间:2011-12-13 05:39:53

标签: iphone objective-c ios xcode

我是iOS开发的新手。

我想从我拥有的文本(.rtf)文件中检索字符串。该文件位于我的应用程序主包中。它的内容是:

#start word1 First word end word2 Second word end //lots of things to be added later

代码:

 path = [[NSBundle mainBundle]pathForResource:@"words" ofType:@"rtf"];
    if(path)
    {
        NSLog(@"path exists");
    }
    NSError *error = nil;

    NSString *file = [[NSString alloc]initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
    if(error)
    {
        NSLog(@"error");
    }
    NSString *finalword= [[NSString alloc]init ];
    NSString *startfrom = [[NSString alloc] initWithFormat:@"word%i",i+1];
    i++;
    NSLog(@"%@",startfrom);
    NSString *wordoftheday = [[NSString alloc]init ];
    NSScanner *scanner = [NSScanner scannerWithString:file];
    [scanner scanUpToString:startfrom intoString:nil];
    [scanner scanUpToString:@"end" intoString:&wordoftheday];
    finalword = [wordoftheday substringFromIndex:[startfrom length]];
    NSLog(@"%@",finalword);
    Word.text = final word;  //change label text
//[final word release];
//[wordoftheday release];
//[file release];

代码工作正常,但它让我遇到内存管理问题。如果我在上一个评论代码中发布变量,应用程序崩溃。

此方法也在我的viewdidload中。我希望标签在用户单击按钮时更改文本。我将不得不在该方法中再次编写相同的代码,这会给我留下更多的内存问题。

2 个答案:

答案 0 :(得分:1)

所以逐一看一下这些内容,关注内存问题,而不是整体策略:

NSString *finalword= [[NSString alloc]init ];

这里你分配/初始化一个新的不可变和空的NSString,然后最后你最终覆盖指向这个的指针。你应该删除这一行。然后你需要将声明向下移动几行:

NSString *finalword = [wordoftheday substringFromIndex:[startfrom length]];

然后你有:

NSString *startfrom = [[NSString alloc] initWithFormat:@"word%i",i+1];

这个你需要稍后发布。或者只是将其更改为:

NSString *startfrom = [NSString stringWithFormat:@"word%i",i+1];

然后你有:

NSString *wordoftheday = [[NSString alloc]init ];

与finalword相同的故事。除非您确实需要定义此变量,以便稍后将其传递给扫描程序。所以改成它:

NSString *wordoftheday = nil;

最后,你可以发布'文件'。那样就好。但是你不想发布'wordoftheday'或'finalword',因为你没有拥有这些字符串。你没有自己创建它们。

还有一个说明:

if(error)

这不是检查加载'文件'时出错的正确方法。你应该检查方法的返回值,然后当且仅当返回值为nil时才查找错误。所以将该行更改为:

if(!file)

(好吧,这不是真正的内存问题,但是我注意到了一个错误。)

我认为这至少就内存问题而言都是如此。我希望有所帮助。

答案 1 :(得分:-1)

将这些变量作为成员变量并在dealloc中释放